执行 Juniper echos 命令的 Paramiko
Paramiko with Juniper echos commands executed
使用 Paramiko 从 Juniper 获取 o/p 时,输出首先显示命令,然后执行命令。下面是代码和输出
import paramiko
import getpass
password = getpass.getpass()
with open('ips.txt','r') as f:
ip = f.read().splitlines()
for device in ip:
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(device, port=22, username='test', password=password, look_for_keys=False, allow_agent=False)
remote_connection = ssh_client.invoke_shell()
remote_connection.send('set cli screen-length 500\n')
remote_connection.send('ping 4.2.2.2 rapid\n')
import time
time.sleep(3)
output = remote_connection.recv(4096)
print(output.decode())
with open('Backup.txt', 'a+') as f:
f.write(output)
f.write("\n********************\n")
ssh_client.close()
输出如下:
Password:
--- JUNOS XXX built XXX
set cli screen-length 500 <---- Is it something relevant with Juniper when running python with paramiko.
ping 4.2.2.2 rapid <-----
{master:0}
XXX> set cli screen-length 500
Screen length set to 500
{master:0}
XXX> ping 4.2.2.2 rapid
PING 4.2.2.2 (4.2.2.2): 56 data bytes
!!!!!
--- 4.2.2.2 ping statistics ---
5 packets transmitted, 5 packets received, 0% packet loss
round-trip min/avg/max/stddev = 43.876/52.403/55.517/4.345 ms
您正在通过在交互式 shell 终端界面上模拟键入命令来执行命令。因此,终端回显您 "type".
也就不足为奇了
要自动执行命令,请不要使用 shell 终端。使用 SSH "exec" 通道。在 Paramiko 那是 SSHClient.exec_command
.
见Python Paramiko - Run command
使用 Paramiko 从 Juniper 获取 o/p 时,输出首先显示命令,然后执行命令。下面是代码和输出
import paramiko
import getpass
password = getpass.getpass()
with open('ips.txt','r') as f:
ip = f.read().splitlines()
for device in ip:
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(device, port=22, username='test', password=password, look_for_keys=False, allow_agent=False)
remote_connection = ssh_client.invoke_shell()
remote_connection.send('set cli screen-length 500\n')
remote_connection.send('ping 4.2.2.2 rapid\n')
import time
time.sleep(3)
output = remote_connection.recv(4096)
print(output.decode())
with open('Backup.txt', 'a+') as f:
f.write(output)
f.write("\n********************\n")
ssh_client.close()
输出如下:
Password:
--- JUNOS XXX built XXX
set cli screen-length 500 <---- Is it something relevant with Juniper when running python with paramiko.
ping 4.2.2.2 rapid <-----
{master:0}
XXX> set cli screen-length 500
Screen length set to 500
{master:0}
XXX> ping 4.2.2.2 rapid
PING 4.2.2.2 (4.2.2.2): 56 data bytes
!!!!!
--- 4.2.2.2 ping statistics ---
5 packets transmitted, 5 packets received, 0% packet loss
round-trip min/avg/max/stddev = 43.876/52.403/55.517/4.345 ms
您正在通过在交互式 shell 终端界面上模拟键入命令来执行命令。因此,终端回显您 "type".
也就不足为奇了要自动执行命令,请不要使用 shell 终端。使用 SSH "exec" 通道。在 Paramiko 那是 SSHClient.exec_command
.
见Python Paramiko - Run command