python中的paramiko模塊是用來實現ssh連接到遠程服務器上的庫,在進行連接的時候,可以用來執行命令,也可以用來上傳文件。
1、得到一個連接的對象
在進行連接的時候,可以使用如下的代碼:
def connect(host): 'this is use the paramiko connect the host,return conn' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try:# ssh.connect(host,username='root',allow_agent=True,look_for_keys=True) ssh.connect(host,username='root',password='root',allow_agent=True) return ssh except: return None
在connect函數中,參數是一個主機的IP地址或者是主機名稱,在執行這個方法之后,如果成功的連接到服務器,那么就會返回一個sshclient對象。
第一步是建立一個SSHClient的對象,然后設置ssh客戶端允許連接不在know_host文件中的機器,然后就嘗試連接服務器,在連接服務器的時候,可以使用兩種方式:一種方式是使用秘鑰的方式,也就是參數look_for_keys,這里用設置密碼尋找,也可以直接使用密碼的方式,也就是直接使用參數password,從而最后返回一個連接的對象。
2、 獲取設置的命令
在進行paramiko連接之后,那么必須要得到需要執行的命令,如下代碼所示:
def command(args,outpath): 'this is get the command the args to return the command' cmd = '%s %s' % (outpath,args) return cmd
在參數中,一個是args,一個outpath,args表示命令的參數,而outpath表示為可執行文件的路徑,例如/usr/bin/ls -l。在其中outpath也就是/usr/bin/ls ,而參數為-l
這個方法主要是用來組合命令,將分開的參數作為命令的一部分進行組裝。
3、 執行命令
在連接過后,可以進行直接執行命令,那么就有了如下的函數:
def exec_commands(conn,cmd): 'this is use the conn to excute the cmd and return the results of excute the command' stdin,stdout,stderr = conn.exec_command(cmd) results=stdout.read() return results
在此函數中,傳入的參數一個為連接的對象conn,一個為需要執行的命令cmd,最后得到執行的結果,也就是stdout.read(),最后返回得到的結果
4、 上傳文件
在使用連接對象的時候,也可以直接進行上傳相關的文件,如下函數:
def copy_moddule(conn,inpath,outpath): 'this is copy the module to the remote server' ftp = conn.open_sftp() ftp.put(inpath,outpath) ftp.close() return outpath
此函數的主要參數為,一個是連接對象conn,一個是上傳的文件名稱,一個上傳之后的文件名稱,在此必須寫入完整的文件名稱包括路徑。
做法主要是打開一個sftp對象,然后使用put方法進行上傳文件,最后關閉sftp連接,最后返回一個上傳的文件名稱的完整路徑
新聞熱點
疑難解答