该脚本实现SecurtCRT登录跳板机,在跳板机上SSH顺序登录多台设备,执行相应命令行,并记录日志。
可实现多台设备执行同一个命令行文件,也可调整代码实现不同的设备执行不同的命令行文件。
注:在SecureCRT上调用脚本时,py脚本和ip.txt cmd.txt要放在同一个目录下。
源代码如下:
# $language = "python"
# $interface = "1.0"
import time
import os
nceip = 'x.x.x.x' # 跳板机IP地址
sopuser = 'xxx' # 跳板机登录用户名
soppasswd = 'xxx' # 跳板机登录密码
tacasuser = 'xxx' # 登录设备用户名
tacaspwd = 'xxx' # 登录设备密码
iptxt = '' # ip.txt, 登录设备IP地址的txt文件,每一行一个IP地址
cmdtxt = '' # cmd.txt, 需要执行的命令行,每行一个命令
LogFilePath = r'C:\\\xxx' # 保存日志log的路径
current_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())) # 当前时间,用于命名log文件
def main():
crt.Screen.Synchronous = True
proxy = '/SSH2 /L %s /PASSWORD %s %s' % (sopuser, soppasswd, nceip)
iptxt = os.path.join(os.getcwd(), 'ip.txt')
with open(iptxt, 'r') as ipfile:
host_list = ipfile.readlines()
for host in host_list:
host = host.replace('\n', '')
crt.Session.ConnectInTab(proxy)
time.sleep(1)
crt.Screen.WaitForString('~]$')
device = 'ssh %s@%s\r' % (tacasuser, host)
crt.Screen.Send(device)
time.sleep(1)
result = crt.Screen.WaitForStrings(['password:', 'connecting (yes/no/[fingerprint])?'])
if result == 1:
crt.Screen.Send(tacaspwd+'\r')
crt.Screen.Send('\r')
if result == 2:
crt.Screen.Send('yes\r')
crt.Screen.WaitForString('password:')
crt.Screen.Send(tacaspwd+'\r')
crt.Screen.WaitForString('H>')
sys_name = log_name()
crt.Session.LogFileName = LogFilePath + '\\' + sys_name + "_" + host + "_" + current_time + "_log.txt "
crt.Session.Log(True)
time.sleep(1)
# cmdtxt = os.path.join(os.getcwd(), host + '_' + sys_name + '.txt') # 用于不同IP地址的设备,执行不同命令行txt文件
cmdtxt = os.path.join(os.getcwd(), 'cmd.txt')
with open(cmdtxt, 'r') as cmdfile:
cmd_list = cmdfile.readlines()
for cmd in cmd_list:
c = cmd.replace('\n', '')
s = sys_name + '>'
crt_send(c, s)
time.sleep(5)
crt.Session.Disconnect()
def log_name():
rowIndex = crt.Screen.CurrentRow
colindex = crt.Screen.CurrentColumn - 1
chushi_name = crt.Screen.Get(rowIndex, 1, rowIndex, colindex)
name = chushi_name.strip('<>')
return name
def crt_send(c, s):
crt.Screen.Send(c + '\r')
crt.Screen.WaitForString(s)
time.sleep(1)
main()