python脚本使用一个csv文件中的值在另一个脚本中执行命令

时间:2019-07-19 06:46:18

标签: python python-2.7 scripting python-2.6

请在下面建议如何实现。
我想在下面的脚本中使用输入文件中的第3列值来执行如下所示的命令
在行号为Script的脚本中使用此命令。 26

telnet.write("**show run interface gigabitEthernet 1**")

show run interface gigabitEthernet 5025
show run interface gigabitEthernet 9
show run interface gigabitEthernet 38

并且要通过使用单个文件中第3列的所有值来收集此命令生成的输出
我认为“ for循环”必须包含在此脚本中的某个位置,以便可以从输入文件中使用所有第3列的值。 或必须将第3列的值作为参数传递给此脚本

输入文件:

CPU,facility,instance,cpu-used,cpu-allc,mem-used,mem-allc,files-used,files-allc,sessions-used,sessions-allc
1/0,sessmgr,5025,0.23%,50%,98.90M,230.0M,31,500,--,--
1/0,sessmgr,9,31%,100%,639.1M,900.0M,41,500,3588,12000
1/0,sessmgr,38,30%,100%,538.3M,900.0M,37,500,3580,12000
1/0,sessmgr,52,29%,100%,533.7M,900.0M,37,500,3592,12000
1/0,sessmgr,75,28%,100%,548.5M,900.0M,35,500,3587,12000
1/0,sessmgr,91,29%,100%,539.1M,900.0M,35,500,3578,12000

代码:

import telnetlib
import threading
import time
import re


class myThread (threading.Thread):
   def __init__(self, device,out):
      threading.Thread.__init__(self)
      self.device = device
      self.f = f
   def run(self):
      self.out = telNetCall(self.device)

def telNetCall(ip):
 host  = ip
 m = 'ok'
 user  = "xyz"
 password = "xyz"
 telnet  = telnetlib.Telnet(host)
 telnet.read_until('Username: ', 3)
 telnet.write(user + '\r')
 telnet.read_until('Password: ', 3)
 telnet.write(password + '\r\n\n\n')
 telnet.write("term len 0"+"\r\n")
 telnet.write("**show run interface gigabitEthernet 1**")
 telnet.write("\r\n\n")
 telnet.write('exit' + '\r')
 a=telnet.read_all()
 f = open("output/"+host+".txt", 'w')
 f.write(str(a))
 f.close()
 telnet.close()
 print host,"done"
 return m



ip = [i.strip() for i in open("LEFT")]
v= []
ip_list = []
for c in ip:
 ip_list.append(c)
for i in range(0,31):
   ip_list.append('')

num_loop = len(ip_list)//30

error_file = open("Error.txt",'w')
f = open("abcd_ios.txt",'w')

for loop in range(0,num_loop):
 threads = []
 x = 0
 for dev in range(0+(loop*30),30+(loop*30)+1):
  x+=1
  print dev
  out = []
  threads.append(myThread(ip_list[dev],out))


 for th in threads:
    th.start()

 ##Wait for all threads to complete
 for t in threads:
    t.join()
 for t in threads:
  try:
    for o in t.out:
        if re.match(".*\d+.*",str(o)):
            f.write(t.device+"\t"+str(o)+"\n")
  except AttributeError:
     error_file.write(t.device+'\n')
     continue

0 个答案:

没有答案