配合 getpass 模块和 input() 函数实现交互式的 SSH ⽤户名和密码输⼊。
配合 for loop 同时给 5 台交换机配置 VLAN 201 ⾄ 205 。
# import 导包
import getpass
import paramiko
import time
# 定义两个字符串变量
username = input("Username: ")
print('=-=-=-=-=-=-=-=-=-=-=-=-=-=')
password = getpass.getpass("Password: ")
print('=-=-=-=-=-=-=-=-=-=-=-=-=-=')
for i in range(201, 206):
ip = '192.168.8.' + str(i)
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip, username=username, password=password, allow_agent=False, look_for_keys=False)
command = ssh_client.invoke_shell()
print('=-=-=-=-=-=-=-=-=-=-=-=-=-=')
print('已经成功登陆交换机 Layer3Switch-' + str(i - 200) + ' ' + ip)
# 关闭分屏功能
command.send('screen-length 0 temporary\n')
# 进⼊系统视图
command.send('sys\n')
for j in range(201, 206):
print('正在创建 VLAN :' + str(j))
command.send('vlan ' + str(j) + '\n')
time.sleep(1)
command.send('desc Python_Vlan' + str(j) + '\n')
time.sleep(1)
command.send('return\n')
command.send('save\n')
command.send('Y\n')
time.sleep(2)
output = command.recv(65535).decode('ASCII')
print(output)
ssh_client.close()
C:\Users\82127\.conda\envs\pythonProject\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2022.1.1\plugins\python-ce\helpers\pydev\pydevd.py" --multiprocess --qt-support=auto --client 127.0.0.1 --port 51862 --file E:/log/python/pythonProject/Demo02.py
已连接到 pydev 调试器(内部版本号 221.5591.52)Username: =-=-=-=-=-=-=-=-=-=-=-=-=-=
Warning: Password input may be echoed.
Password: =-=-=-=-=-=-=-=-=-=-=-=-=-=
=-=-=-=-=-=-=-=-=-=-=-=-=-=
已经成功登陆交换机 Layer3Switch-1 192.168.8.201
正在创建 VLAN :201
正在创建 VLAN :202
正在创建 VLAN :203
正在创建 VLAN :204
正在创建 VLAN :205
Info: The max number of VTY users is 5, and the number
of current VTY users on line is 1.
The current login time is 2022-05-30 23:56:33.
<LSW1>screen-length 0 temporary
Info: The configuration takes effect on the current user terminal interface only.
<LSW1>sys
Enter system view, return user view with Ctrl+Z.
[LSW1]vlan 201
[LSW1-vlan201]desc Python_Vlan201
[LSW1-vlan201]vlan 202
[LSW1-vlan202]desc Python_Vlan202
[LSW1-vlan202]vlan 203
[LSW1-vlan203]desc Python_Vlan203
[LSW1-vlan203]vlan 204
[LSW1-vlan204]desc Python_Vlan204
[LSW1-vlan204]vlan 205
[LSW1-vlan205]desc Python_Vlan205
[LSW1-vlan205]return
<LSW1>save
The current configuration will be written to the device.
Are you sure to continue?[Y/N]Y
Info: Please input the file name ( *.cfg, *.zip ) [vrpcfg.zip]:
=-=-=-=-=-=-=-=-=-=-=-=-=-=
已经成功登陆交换机 Layer3Switch-2 192.168.8.202
正在创建 VLAN :201
正在创建 VLAN :202
正在创建 VLAN :203
正在创建 VLAN :204
正在创建 VLAN :205
Info: The max number of VTY users is 5, and the number
of current VTY users on line is 1.
The current login time is 2022-05-30 23:56:46.
<Huawei>screen-length 0 temporary
Info: The configuration takes effect on the current user terminal interface only.
<Huawei>sys
Enter system view, return user view with Ctrl+Z.
[Huawei]vlan 201
[Huawei-vlan201]desc Python_Vlan201
[Huawei-vlan201]vlan 202
[Huawei-vlan202]desc Python_Vlan202
[Huawei-vlan202]vlan 203
[Huawei-vlan203]desc Python_Vlan203
[Huawei-vlan203]vlan 204
[Huawei-vlan204]desc Python_Vlan204
[Huawei-vlan204]vlan 205
[Huawei-vlan205]desc Python_Vlan205
[Huawei-vlan205]return
<Huawei>save
The current configuration will be written to the device.
Are you sure to continue?[Y/N]Y
Info: Please input the file name ( *.cfg, *.zip ) [vrpcfg.zip]:
=-=-=-=-=-=-=-=-=-=-=-=-=-=
已经成功登陆交换机 Layer3Switch-3 192.168.8.203
正在创建 VLAN :201
正在创建 VLAN :202
正在创建 VLAN :203
正在创建 VLAN :204
正在创建 VLAN :205
Info: The max number of VTY users is 5, and the number
of current VTY users on line is 1.
The current login time is 2022-05-30 23:56:59.
<Huawei>screen-length 0 temporary
Info: The configuration takes effect on the current user terminal interface only.
<Huawei>sys
Enter system view, return user view with Ctrl+Z.
[Huawei]vlan 201
[Huawei-vlan201]desc Python_Vlan201
[Huawei-vlan201]vlan 202
[Huawei-vlan202]desc Python_Vlan202
[Huawei-vlan202]vlan 203
[Huawei-vlan203]desc Python_Vlan203
[Huawei-vlan203]vlan 204
[Huawei-vlan204]desc Python_Vlan204
[Huawei-vlan204]vlan 205
[Huawei-vlan205]desc Python_Vlan205
[Huawei-vlan205]return
<Huawei>save
The current configuration will be written to the device.
Are you sure to continue?[Y/N]Y
Info: Please input the file name ( *.cfg, *.zip ) [vrpcfg.zip]:
=-=-=-=-=-=-=-=-=-=-=-=-=-=
已经成功登陆交换机 Layer3Switch-4 192.168.8.204
正在创建 VLAN :201
正在创建 VLAN :202
正在创建 VLAN :203
正在创建 VLAN :204
正在创建 VLAN :205
Info: The max number of VTY users is 5, and the number
of current VTY users on line is 1.
The current login time is 2022-05-30 23:57:12.
<Huawei>screen-length 0 temporary
Info: The configuration takes effect on the current user terminal interface only.
<Huawei>sys
Enter system view, return user view with Ctrl+Z.
[Huawei]vlan 201
[Huawei-vlan201]desc Python_Vlan201
[Huawei-vlan201]vlan 202
[Huawei-vlan202]desc Python_Vlan202
[Huawei-vlan202]vlan 203
[Huawei-vlan203]desc Python_Vlan203
[Huawei-vlan203]vlan 204
[Huawei-vlan204]desc Python_Vlan204
[Huawei-vlan204]vlan 205
[Huawei-vlan205]desc Python_Vlan205
[Huawei-vlan205]return
<Huawei>save
The current configuration will be written to the device.
Are you sure to continue?[Y/N]Y
Info: Please input the file name ( *.cfg, *.zip ) [vrpcfg.zip]:
=-=-=-=-=-=-=-=-=-=-=-=-=-=
已经成功登陆交换机 Layer3Switch-5 192.168.8.205
正在创建 VLAN :201
正在创建 VLAN :202
正在创建 VLAN :203
正在创建 VLAN :204
正在创建 VLAN :205
Info: The max number of VTY users is 5, and the number
of current VTY users on line is 1.
The current login time is 2022-05-30 23:57:24.
<Huawei>screen-length 0 temporary
Info: The configuration takes effect on the current user terminal interface only.
<Huawei>sys
Enter system view, return user view with Ctrl+Z.
[Huawei]vlan 201
[Huawei-vlan201]desc Python_Vlan201
[Huawei-vlan201]vlan 202
[Huawei-vlan202]desc Python_Vlan202
[Huawei-vlan202]vlan 203
[Huawei-vlan203]desc Python_Vlan203
[Huawei-vlan203]vlan 204
[Huawei-vlan204]desc Python_Vlan204
[Huawei-vlan204]vlan 205
[Huawei-vlan205]desc Python_Vlan205
[Huawei-vlan205]return
<Huawei>save
The current configuration will be written to the device.
Are you sure to continue?[Y/N]Y
Info: Please input the file name ( *.cfg, *.zip ) [vrpcfg.zip]:
进程已结束,退出代码0
您提供的Python脚本使用了paramiko库来通过SSH连接到一系列网络设备(在这个例子中似乎是交换机),并在这些设备上执行一系列命令来创建VLAN。以下是对您脚本的一些分析和建议:
导入库和获取用户凭据:
您正确地导入了所需的库,并安全地获取了用户名和密码。
循环遍历IP地址:
您使用了一个for循环来遍历一个IP地址范围(192.168.8.201到192.168.8.205)。
SSH连接:
您为每个IP地址创建了一个SSH客户端,并设置了自动添加未知主机密钥的策略。
您使用提供的用户名和密码连接到每个设备。
发送命令:
您发送了命令来关闭分屏功能、进入系统视图,并循环创建VLAN。
您为每个VLAN设置了描述,并在创建完所有VLAN后保存配置。
接收输出:
您尝试接收并打印来自交换机的输出。但是,由于您是在一个持续交互的shell中发送命令,recv方法可能不会立即返回所有输出,特别是如果交换机需要更多时间来处理命令或输出被缓冲了。
关闭连接:
您在每个循环迭代结束时关闭了SSH连接。
建议:
输出处理:由于recv可能不会立即返回所有输出,您可能需要多次调用recv或在发送每个命令后检查输出,直到没有新的输出为止。这可以通过在一个循环中调用recv并检查返回的输出是否为空字符串来实现。
错误处理:您的脚本没有处理可能发生的异常,例如SSH连接失败、命令执行错误等。您应该添加try-except块来捕获这些异常,并适当地处理它们(例如,打印错误消息并继续下一个IP,或完全停止脚本)。
性能优化:如果您正在处理大量设备或命令,考虑使用多线程或异步IO来加速脚本的执行。
安全性:虽然您已经使用了getpass来隐藏密码输入,但将凭据硬编码到脚本中(即使是以变量的形式)也不是最佳实践。考虑使用更安全的方法来存储和检索凭据,例如环境变量、加密的配置文件或使用密钥管理服务。
代码清晰度:考虑将功能分解为函数,以提高代码的可读性和可维护性。
以下是一个添加了基本错误处理和多次接收输出的示例代码段:
python
…(之前的代码保持不变)
try:
ssh_client.connect(hostname=ip, username=username, password=password, allow_agent=False, look_for_keys=False)
command = ssh_client.invoke_shell()
print(‘=-=-=-=-=-=-=-=-=-=-=-=-=-=’)
print(‘已经成功登陆交换机 Layer3Switch-’ + str(i - 200) + ’ ’ + ip)
# …(发送命令的代码保持不变)
# 接收输出
all_output = ''
while True:
output = command.recv(65535).decode('ASCII')
if not output: # 如果没有新的输出,则停止循环
break
all_output += output # 将输出添加到总输出中
print(all_output) # 打印所有接收到的输出
except paramiko.ssh_exception.NoValidConnectionsError:
print(f"无法连接到 {ip}“)
except paramiko.AuthenticationException:
print(f"认证失败:{ip}”)
except Exception as e:
print(f"发生错误:{e}")
finally:
ssh_client.close() # 确保无论如何都关闭连接
请注意,这个示例中的错误处理是基本的,并且可能需要根据您的具体需求进行调整。