How do you execute multiple commands in a single session in Paramiko? (Python)

前端 未结 6 1212
礼貌的吻别
礼貌的吻别 2020-11-27 13:50
def exec_command(self, command, bufsize=-1):
    #print \"Executing Command: \"+command
    chan = self._transport.open_session()
    chan.exec_command(command)
             


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 14:06

    Non-Interactive use cases

    This is a non-interactive example... it sends cd tmp, ls and then exit.

    import sys
    sys.stderr = open('/dev/null')       # Silence silly warnings from paramiko
    import paramiko as pm
    sys.stderr = sys.__stderr__
    import os
    
    class AllowAllKeys(pm.MissingHostKeyPolicy):
        def missing_host_key(self, client, hostname, key):
            return
    
    HOST = '127.0.0.1'
    USER = ''
    PASSWORD = ''
    
    client = pm.SSHClient()
    client.load_system_host_keys()
    client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
    client.set_missing_host_key_policy(AllowAllKeys())
    client.connect(HOST, username=USER, password=PASSWORD)
    
    channel = client.invoke_shell()
    stdin = channel.makefile('wb')
    stdout = channel.makefile('rb')
    
    stdin.write('''
    cd tmp
    ls
    exit
    ''')
    print stdout.read()
    
    stdout.close()
    stdin.close()
    client.close()
    

    Interactive use cases
    If you have an interactive use case , this answer won't help... I personally would use pexpect or exscript for interactive sessions.

提交回复
热议问题