【问题标题】:Get command prompt via "sudo su -" then run command using Paramiko exec_command通过“sudo su -”获取命令提示符,然后使用 Paramiko exec_command 运行命令
【发布时间】:2022-02-20 03:14:39
【问题描述】:

你能帮我关注一下吗? 我需要以用户身份登录,然后sudo su - 然后运行命令 ex。 parted -l 使用帕拉米科 exec_command 当我运行以下代码时,它会挂起。请让我知道如何在被绞死之前进行检查。

with SSHClient() as client:
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('172.20.xxx.xx', port=22, username='xxx', password='xxxxxxx',timeout=15.0)
    transport = client.get_transport()
    session = transport.open_session()
    session.set_combine_stderr(True)
    session.get_pty()
    session.exec_command('sudo su -')
    time.sleep(5)
    stdin = session.makefile('wb', -1)
    stdout = session.makefile('rb', -1)
    stderr = session.makefile_stderr('rb', -1)
    stdin.write('xxxxxxx' + '\n')
    stdin.flush()
    session.exec_command('parted -l')
    time.sleep(5)
    stdin = session.makefile('wb', -1)
    stdout = session.makefile('rb', -1)
    stderr = session.makefile_stderr('rb', -1)
    stdin.flush()
    for line in stdout.read().splitlines():
        print 'LINE: %s' % (line)

【问题讨论】:

    标签: python ssh paramiko


    【解决方案1】:

    您要检查单个parted 命令的结果吗?如果要检查单个命令的结果,请不要运行 shell(在这种情况下为su)。只运行命令:

    sudo su -c "parted -l"
    

    另见Executing command using "su -l" in SSH using Python

    那么你可以使用recv_exit_status():
    How can you get the SSH return code using Paramiko?


    如果您出于任何原因想保持当前方法,请参阅:

    【讨论】: