如何用帕拉米科运行sudo?(Python)

2024-04-30 12:53:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过的:

  1. invoke_shell()然后channel.sendsu然后发送密码导致不是根用户
  2. invoke_shell()然后channel.exec_command导致“通道关闭”错误
  3. _transport.open_session()然后channel.exec_command导致不是根
  4. invoke_shell()然后写入stdin并刷新它,结果不是根目录

Tags: 用户密码session错误stdinchannelopenshell
3条回答

invoke_shell为我这样工作:

import paramiko, getpass, re, time

ssh_client = paramiko.SSHClient()   
ssh_client.connect( host )
sudo_pw = getpass.getpass("sudo pw for %s: " % host)
command = "sudo magicwand"

channel = ssh_client.invoke_shell() 
channel.send( command )       
# wait for prompt             
while not re.search(".*\[sudo\].*",channel.recv(1024)): time.sleep(1)
channel.send( "%s\n" % sudo_pw )

很抱歉,我没有时间回答细节问题,但我可以使用thisadvise在paramiko上实现sudo命令

import paramiko
l_password = "yourpassword"
l_host = "yourhost"
l_user = "yourusername"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(l_host, username=l_user, password=l_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 -k dmesg")
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
#you have to check if you really need to send password here 
stdin.write(l_password +'\n')
stdin.flush()
for line in stdout.read().splitlines():        
    print 'host: %s: %s' % (l_host, line)

看看这个例子:

ssh.connect('127.0.0.1', username='jesse', 
    password='lol')
stdin, stdout, stderr = ssh.exec_command(
    "sudo dmesg")
stdin.write('lol\n')
stdin.flush()
data = stdout.read.splitlines()
for line in data:
    if line.split(':')[0] == 'AirPort':
        print line

此处的示例提供了更多解释: http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/

希望有帮助!

相关问题 更多 >