如何用paramiko运行sudo?(蟒蛇)

Tak*_*kun 14 python ssh sudo paramiko

我尝试过的:

  1. invoke_shell()然后channel.send su发送密码导致不是root
  2. invoke_shell()然后channel.exec_command导致"频道关闭"错误
  3. _transport.open_session()然后channel.exec_command导致不是根
  4. invoke_shell() 然后写入stdin并冲洗它导致不是root

W0b*_*ble 20

检查这个例子:

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
Run Code Online (Sandbox Code Playgroud)

例如在这里找到更多的解释: http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/

希望能帮助到你!

  • 如果您的sudoer需要密码,这将无效:"sudo:no tty present and no askpass program" (5认同)
  • 我的坏,我没有检查stderr,应该说必须使用`get_pty = True`,所以你需要使用:`ssh.exec_command('your command',get_pty = True)` (3认同)
  • 好的,您提供的链接中的riskable评论解决了上述问题: stdin, stdout, stderr = ssh.exec_command("sudo -S %s" % command) # If stdout is still open then sudo is Ask us for a password if stdout .channel.close 为 False: stdin.write('%s\n' % 密码) stdin.flush() (2认同)
  • get_pty = True有帮助。没有此密码提示不会出现。 (2认同)

小智 6

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 )
Run Code Online (Sandbox Code Playgroud)


Ami*_*ein 5

AlexS 微调的答案(我现在在生产中使用它)将是:

def sudo_run_commands_remote(command, server_address, server_username, server_pass, server_key_file):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=server_address,
                username=server_username,
                password=server_pass,
                key_filename=server_key_file)
    session = ssh.get_transport().open_session()
    session.set_combine_stderr(True)
    session.get_pty()
    session.exec_command("sudo bash -c \"" + command + "\"")
    stdin = session.makefile('wb', -1)
    stdout = session.makefile('rb', -1)
    stdin.write(server_pass + '\n')
    stdin.flush()
    print(stdout.read().decode("utf-8"))
Run Code Online (Sandbox Code Playgroud)

如果您不使用密钥文件,则删除方法的key_filename一部分,connect相反,如果您只使用没有密码的密钥,则删除该password部分。

关于这一点的一些注意事项是,它具有多命令能力。这意味着在正在运行bashroot,所以你可以尽可能多的命令,你可以在只与他们分开单次运行;