从远程卡住的 paramiko ssh 注销

Logout from remote stuck paramiko ssh

这个问题与 有关,我尝试用另一种方法来解决我当前的问题。

因为 paramiko 循环永远在等待用户输入命令。我无法杀死,有 pid 或做任何事情来继续。

    stdin, stdout, stderr = self.connection.exec_command(command)

    while not stdout.channel.exit_status_ready():
        if stdout.channel.recv_ready():
            alldata = stdout.channel.recv(1024)
            rl, wl, xl = select.select([stdout.channel], [], [], 0.0)
            if len(rl) > 0:
                self.logger.info(stdout.channel.recv(1024), )

哪种方法,我尝试使用 paramiko 登录到其他用户 (root) 并杀死这个远程用户。

在根目录中:

$ skill -KILL -u remoteuser

我尝试使用线程,但因为它无法处理。执行下一个线程失败。

thread1 = threading.Thread(target=remoteuser_stuckfreeze)
thread2 = threading.Thread(target=roottokillremoteuser)
thread1.start()
thread2.start()
thread1.join()
thread2.join()

谢谢。

我最终使用了 fabric

from fabric.tasks import execute
from fabric.api import run, settings, env

def remoteuser_login(self):
    env.user = 'remoteuser'
    env.password = 'remotepassword'
    with settings(prompts={'>': 'q\n'}):
        run('exit')

并执行那个

execute(remoteuser_login, host='ipaddress')

另外要强调的是,fabric 也有命令超时,我们可以将其设置为在卡住时从远程退出。

--命令超时=N

http://docs.fabfile.org/en/1.13/usage/fab.html

替代使用parallel-ssh

from pssh import ParallelSSHClient
client = ParallelSSHClient(['myhost'], user='remoteuser',
                           password='remotepassword')
output = client.run_command(<..>)
# Can send data using stdin channel if needed
# output.stdin.write('write on user prompt\n')
# output.stdin.flush()
stdout = list(output.stdout)

有一个 channel_timeout 设置在 N 秒不活动后超时,相当于命令超时。

根据我和其他人的经验,建议使用库作为 Fabric 的不同 paramiko 是非常错误的。