一、程序說明
ssh客戶端實現主要有以下四個問題:
第一個問題是在python中ssh客戶端使用哪個包實現----我們這里使用的是paramiko
第二個問題是怎么連接服務器----連接服務器直接使用connect()函數就可以了,有個坑是不在known_hosts文件中的機器默認不允許連接需要處理一下
第三個問題是連上之后怎么執行命令----連上之后直接用exec_command()函數就可以執行命令
第四個問題是怎么讀取命令執行結果----exec_command()函數會返回函數執行結果,用一個參數接收一下就可以了
我們這里整個整序的流程是:
使用用戶名密碼登錄主機----如果登錄成功則執行whoami命令----打印whoami命令結果----退出ssh會話
二、程序源代碼
import logging import sys from paramiko import AuthenticationException from paramiko.client import SSHClient, AutoAddPolicy from paramiko.ssh_exception import NoValidConnectionsError class MySshClient(): def __init__(self): self.ssh_client = SSHClient() # 此函數用於輸入用戶名密碼登錄主機 def ssh_login(self,host_ip,username,password): try: # 設置允許連接known_hosts文件中的主機(默認連接不在known_hosts文件中的主機會拒絕連接拋出SSHException) 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: logging.warning('unknow error') print("Unexpected error:", sys.exc_info()[0]) return 1003 return 1000 # 此函數用於執行command參數中的命令並打印命令執行結果 def execute_some_command(self,command): stdin, stdout, stderr = self.ssh_client.exec_command(command) print(stdout.read().decode()) # 此函數用於退出登錄 def ssh_logout(self): logging.warning('will exit host') self.ssh_client.close() if __name__ == '__main__': # 遠程主機IP host_ip = '192.168.220.129' # 遠程主機用戶名 username = 'root' # 遠程主機密碼 password = 'toor' # 要執行的shell命令;換成自己想要執行的命令 # 自己使用ssh時,命令怎么敲的command參數就怎么寫 command = 'whoami' # 實例化 my_ssh_client = MySshClient() # 登錄,如果返回結果為1000,那么執行命令,然后退出 if my_ssh_client.ssh_login(host_ip,username,password) == 1000: logging.warning(f"{host_ip}-login success, will execute command:{command}") my_ssh_client.execute_some_command(command) my_ssh_client.ssh_logout()
參考: