【发布时间】:2016-06-30 23:19:11
【问题描述】:
* 的向导。我正在尝试使用 paramiko 将命令从 .txt 文件读入 SSH。目前它将从文件的第一行读取并执行它。当我到达第二行时,它会抛出一个 EOFError 并退出。我检查了第二个命令是否使它打印并且它确实打印了,但是它没有执行。我希望有人能够帮助我解决这个问题。这是我的代码:
from paramiko import client
import logging
import os
#Clear the screen before starting the script
os.system('cls')
# Prompting for the user input config file
filename = input('Input configuration filename, the file extension must be attached: ')
# Creating the LOG file for the execution of the config file
logFileName = "LOG" + filename[0:]
try:
logging.basicConfig(filename= logFileName ,format='%(asctime)s %(message)s', level= logging.DEBUG)
print ("The file was created!")
except IOError:
print ("File failed to create")
logging.info("---------------------------------------------------------------------------")
logging.info("NEW CONFIGURATION LOG ENTRY")
logging.info("---------------------------------------------------------------------------")
# Class for creating an SSH client, logging in, letting us write out commands, and close the client.
class ssh:
client = None
def __init__(self, address, username, password):
print ("Connecting to server...")
logging.info('Connecting to server...')
self.client = client.SSHClient()
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
self.client.connect(address, username= username, password= password, look_for_keys= False)
logging.info("Address: " + address)
logging.info("Username: " + username)
print ("Connection successful!")
logging.info('Connection successful!')
def sendCommand(self, command):
if (self.client):
stdin, stdout, stderr = self.client.exec_command(command)
receiveData = b""
while not stdout.channel.exit_status_ready():
receiveData += stdout.channel.recv(1024)
if stdout.channel.recv_ready():
received = stdout.channel.recv(1024)
while received:
receiveData += received
received = stdout.channel.recv(1024)
if receiveData:
print (str(receiveData, "utf8"))
else:
print ("stdout is empty")
else:
print ("Connection failed, check credentials and try again..")
logging.warning('Connection failed, check credentials and try again..')
connection = ssh('0.0.0.0', 'test', 'test')
with open(filename) as f:
for line in f:
print(line)
connection.sendCommand(line)
.txt 文件的内容如下:
配置终端
接口 Gi0/9
描述测试接口
非常感谢您的帮助,谢谢。
【问题讨论】:
-
sendCommand的当前实现有时无法接收服务器输出。和原代码一样,还是简化版? -
@Arnial 和原版一样