python-3.x Ssh套接字已关闭,想要一个Linux Box的交互式Ssh shell自动化

ki0zmccv  于 2023-06-25  发布在  Python
关注(0)|答案(2)|浏览(142)

Ssh套接字已关闭。想要Linux Box的交互式Ssh shell自动化。

import paramiko

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
##Creating Ssh Session

ssh.connect("gfr4123408", port=22, username='rstrusr',password='Password')

stdin,stdout,stderr = ssh.exec_command('symcfg -lockbox reset -ssv')

#Here it asks for password and i want to write password below

stdin.write("Password")

stdin.write('\n')

stdin.flush()

output=stdout.readlines()

print(output)

我得到以下错误:

Traceback (most recent call last):   File "<pyshell#24>", line 1, in
<module>
    stdin.write('password')   File "C:\Users\venkar2\AppData\Local\Programs\Python\Python36\lib\site-packages\paramiko\file.py",
line 402, in write
    self._write_all(data)   File "C:\Users\venkar2\AppData\Local\Programs\Python\Python36\lib\site-packages\paramiko\file.py",
line 519, in _write_all
    count = self._write(data)   File "C:\Users\venkar2\AppData\Local\Programs\Python\Python36\lib\site-packages\paramiko\channel.py",
line 1333, in _write
    self.channel.sendall(data)   File "C:\Users\venkar2\AppData\Local\Programs\Python\Python36\lib\site-packages\paramiko\channel.py",
line 831, in sendall
    sent = self.send(s)   File "C:\Users\venkar2\AppData\Local\Programs\Python\Python36\lib\site-packages\paramiko\channel.py",
line 785, in send
    return self._send(s, m)   File "C:\Users\venkar2\AppData\Local\Programs\Python\Python36\lib\site-packages\paramiko\channel.py",
line 1169, in _send
    raise socket.error('Socket is closed') OSError: Socket is closed

我必须为200多台设备进行配置,如何解决此问题?

9jyewag0

9jyewag01#

你会发现有两件事很有用:

  1. exec_command接受get_pty的可选参数。你可以这样使用它:
(stdin, stdout, stderr) = ssh.exec_command("sudo ls", get_pty = True)

1.将密码扔到stdin中,并返回一行并刷新以确保它被传递。这样可以确保它在询问时收到密码(您可以做一些更复杂的操作来检查它是否确实询问了密码...简单地把它扔进去总是没有给我带来问题,然而。

stdin.write('passwd' + '\n')
stdin.flush()

综上所述,这些应该可以解决您的sudo over paramiko问题。

uttx8gqw

uttx8gqw2#

大多数情况下,此问题与发送两个命令之间的时间有关。我遇到了这个问题。当我在命令之间使用“time.sleep(X)”时,这个问题就消失了。

相关问题