Long-running ssh commands in python paramiko module (and how to end them)

后端 未结 6 1766
野性不改
野性不改 2020-11-30 02:39

I want to run a tail -f logfile command on a remote machine using python\'s paramiko module. I\'ve been attempting it so far in the following fashion:

6条回答
  •  隐瞒了意图╮
    2020-11-30 03:22

    Instead of calling exec_command on the client, get hold of the transport and generate your own channel. The channel can be used to execute a command, and you can use it in a select statement to find out when data can be read:

    #!/usr/bin/env python
    import paramiko
    import select
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.connect('host.example.com')
    transport = client.get_transport()
    channel = transport.open_session()
    channel.exec_command("tail -f /var/log/everything/current")
    while True:
      rl, wl, xl = select.select([channel],[],[],0.0)
      if len(rl) > 0:
          # Must be stdout
          print channel.recv(1024)
    

    The channel object can be read from and written to, connecting with stdout and stdin of the remote command. You can get at stderr by calling channel.makefile_stderr(...).

    I've set the timeout to 0.0 seconds because a non-blocking solution was requested. Depending on your needs, you might want to block with a non-zero timeout.

提交回复
热议问题