2017-08-29 116 views
0

使用paramiko連接到遠程主機。我如何移動目錄並執行unix操作?下面使用ssh連接到遠程主機後執行unix操作

import paramiko 
ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect('remote ip', username='username', password='password') 
ftp = ssh.open_sftp() 
ssh.exec_command('cd /folder1/folder2') 

示例代碼如何執行就像一個目錄列表文件,檢查當前的工作目錄並執行其他的Unix命令操作?

回答

1

這樣(在ls命令爲例):

import paramiko 
import sys 

ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect('x.x.x.x', port=22, username='user', password='pass') 
stdin, stdout, stderr = ssh.exec_command('ls') 

# Wait for the command to terminate 
while not stdout.channel.exit_status_ready(): 
    # Only print data if there is data to read in the channel 
    if stdout.channel.recv_ready(): 
     rl, wl, xl = select.select([stdout.channel], [], [], 0.0) 
     if len(rl) > 0: 
      # Print data from stdout 
      print stdout.channel.recv(1024), 



ssh.close() 
+0

我想這一點,但是當我的stdout打印不會列出目錄中的所有文件。我從>> – Harikrishna

+0

不知道。它在這裏起作用。看看這個Paramiko文檔(命令SSHClient):http://docs.paramiko.org/en/2.2/api/client.html –

+0

我編輯了我的代碼,添加一個等待循環stdout在打印之前終止。 –

相關問題