Невозможно произвести с устройства, сделал отдельную функцию при запуске простого метода, в котором у меня есть список устройств и команды.
Но из этого скрипта кажется, что я не могу отправить команду на устройство?Я не уверен, может ли скрипт успешно подключиться.Поэтому я поставил отпечаток на соединении с устройством только для определения местоположения.
На выходе из распечатки подключено 0 <-из команды beg_rm ЭТО КОМАНДА show ip int краткое <-send_cmd </p>
Хотелось бы спросить, правильный ли мой метод в команде подключения и отправкииспользуя эту функцию и аргумент?
#!/usr/bin/python2
#Required Modules
import sys
sys.path.append("/home/lab/Desktop/pexpect-2.3")
import sys, pexpect, re, getpass, threading, subprocess, os, time
#from queue import Queue
os.system("clear")
### TEST THE IP ADDRESS IF REACHABLE
def ping_ip(ip):
#global gips
rstlongstr = ''
(output,error) = subprocess.Popen((['ping', ip, '-c', '2']), stdin=subprocess.PIPE, stdout=subprocess.PIPE).communicate()
if b'bytes from' in output:
#rstlongstr = rstlongstr + ip
#print rstlongstr
return "Reachable" + ip
elif b'Host Unreachable' in output:
return "Down"
else:
return "UNKNOWN"
### SEND COMMAND TO DEVICE
def send_cmd(child,com):
print "THIS IS THE COMMAND", com
child.sendline(com)
child.expect("#")
print(child.before)
return result
### CONNECT TO DEVICE
def beg_rm(ip,uname,ppass,enpass):
print "Begin remote connection",ip
print "\nCRED",uname,ppass,enpass
child = pexpect.spawn('ssh %s@%s' % (uname, ip))
i = child.expect(['[P|p]assword: ','[U|u]sername: ','continue connecting (yes/no)?','#'],timeout=5)
if i == 0:
child.sendline(ppass)
child.expect('>')
child.sendline('enable')
child.expect('Password: ')
child.sendline(enpass)
print "Connected 0"
return i
elif i == 1:
child.sendline(uname)
child.expect('Password: ')
child.sendline(ppass)
child.expect('>')
child.sendline(enpass)
print "Connected 1"
return i
elif i == 2:
child.sendline('yes')
i = child.expect([pexpect.TIMEOUT, '[P|p]assword: '])
if i == 0:
print "Error connecting ",ip
return
child.sendline(ppass)
child.expect('>')
child.sendline('enable')
child.expect('Password: ')
child.sendline(enpass)
print "Connected 2"
return i
elif i == 3:
pass
def main():
print('-'*50)
while True:
print('------------------------- ue Network Tools -------------------------------')
print('--- *********************************************************************** ---')
print('-'*80)
print'[1] Troubleshoot'
print'[2] Custom Tshoot'
print'[3] Wireless LAN'
print'[4] Confinder'
print'[q] exit\n'
#Select Function
input_select = raw_input('Please select a function: ')
input_select = str(input_select)
if input_select == 'q' or input_select == 'Q':
sys.exit()
elif input_select == '1':
#Read the txt file
devtxt = open('devices.txt')
devlist = devtxt.read().splitlines()
print devlist
cmdtxt = open('command.txt')
cmdlist = cmdtxt.read().splitlines()
print cmdlist
#tuname = raw_input("TACACS Username: ")
#tpass=getpass.getpass("TACACS Password: ")
#epass=getpass.getpass("Enable Password: ")
tuname = "test"
tpass = "test"
epass = "enter"
#LIST
gips = []
threadslist = []
#Verify Reachability
for ips in devlist:
print "Processing the list to function", ips
response = ping_ip(ips)
result = ('%s \n' % (response))
print result
if re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})',str(response)):
forgips = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})',str(response))
strgips = ''.join(forgips)
#print "FORGIPS 2",strgips
gips.append(strgips)
pass
else:
pass
print "\nList of reachable devices to be sent for threading:\n", gips
## LOOP REACHABLE DEVICE AND COMMAND
for x in gips:
child = beg_rm(x,tuname,tpass,epass)
for y in cmdlist:
send_cmd(child,y)
if __name__ == '__main__':
main()
Трассировка назад
Traceback (most recent call last):
File "2jb.py", line 142, in <module>
main()
File "2jb.py", line 139, in main
send_cmd(child,y)
File "2jb.py", line 31, in send_cmd
child.sendline(com)
AttributeError: 'int' object has no attribute 'sendline'