2017-02-09 124 views
0

我需要運行一個python腳本ssh到遠程主機。在遠程主機上運行的第一個命令是「sudo su」。我有它的密碼。然後,我需要cd到一個目錄並將文件複製到我的本地框。我嘗試了兩種方式。他們兩個都不行。Python的ssh命令來更改用戶

腳本#1:

ssh=paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect(hostName,username='e0258595',password='<password>') 
stdin,stdout,stderr = ssh.exec_command("sudo su; whoami") 
stdin.write('password\n') 
stdin.flush() 
data = stdout.readlines() 
for line in data: 
    print line 

輸出仍然是e0258595。

腳本#2:

ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect(hostName, username="e0258595", password="<password>") 
transport = ssh.get_transport() 
session = transport.open_session() 
session.set_combine_stderr(True) 
session.get_pty() 
#for testing purposes we want to force sudo to always to ask for password. because of that we use "-k" key 
session.exec_command("sudo su; whoami") 
stdin = session.makefile('wb', -1) 
stdout = session.makefile('rb', -1) 
#you have to check if you really need to send password here 
stdin.write("<password>"+'\n') 
stdin.flush() 
data = stdout.readlines() 
for line in data: 
    print line 

這一個只掛。

什麼問題?

+1

您應該使用'sudo -s'或'sudo -i'作爲交互式root shell。 –

+0

另外,嘗試一次發送一個命令。 – 9000

回答

0

你試過用get_pty = True嗎?

stdin,stdout,stderr = ssh.exec_command("sudo su; whoami", get_pty=True)