Python ssh client

使用Python實現ssh client功能

依賴模塊:paramiko
安裝方式:pip3 install paramiko 或者 sudo apt-get install python-paramiko

具體實現的代碼:

#導入paramiko模塊
import paramiko
#導入ssh client模塊
from paramiko.client import SSHClient, AutoAddPolicy
#導入異常處理
from paramiko import AuthenticationException
from paramiko.ssh_exception import NoValidConnectionsError

#創建SshClient 類
class SshClient():
	#初始化
    def __init__(self):
        self.ssh_client = SSHClient()
	#登錄
    def ssh_login(self, host_ip, username, password):
        try:
        	#允許連接不在known_hosts文件中的主機,及自動輸入yes
            self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
            self.ssh_client.connect(host_ip, port=22, username=username, password=password)
        except AuthenticationException:
            logging.warning('username or password error')
            return 1001
        except NovalidConnectionsError:
            logging.warning('connect time out')
            return 1002
        except:
            print("Unexpected error:", sys.exc_info()[0])
            return 1003
        return 1000

    def execute_some_command(self, command):
    	#執行命令,打印結果
        stdin, stdout, stderr = self.ssh_client.exec_command(command)
        print(stdout.read().decode())

    def ssh_logout(self):
    	#註銷鏈接
        self.ssh_client.close()


if __name__=="__main__":
    command = "cd"
    ssh = SshClient()
    if ssh.ssh_login(host_ip="127.0.0.1", username="zhang", password="123456") == 1000:
        ssh.execute_some_command(command)
        ssh.ssh_logout()
        print("success ssh connent")
    else:
        print("error connect to host ")

參考文章:

  1. Python—實現ssh客戶端(連接遠程服務器)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章