有时候我们需要批量执行一些命令,比如网络设备批量开局,服务器定时重启服务类似的任务,如果要手动的话就会比较费时费力,我们可以用一个python小脚本来实现这些功能,当然这个只是一个工具的雏形,具体的的需要你根据自己的需求进行定制和修改
# 建立一个sshclient对象
import paramiko
import sys
ssh = paramiko.SSHClient()
# 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 调用connect方法连接服务器
ssh.connect(hostname='192.168.1.1', port=22, username='root', password='123456')
# 执行命令
stdin, stdout, stderr = ssh.exec_command('你需要执行的命令')
# 结果放到stdout中,如果有错误将放到stderr中
print(stdout.read().decode())
if not stderr == '':
print(stderr)
# 关闭连接
ssh.close()
sys.exit()
下面有个多服务器的示例,也加入了日志,方便查看结果
import paramiko
import sys
import logging
# 设置日志配置
logging.basicConfig(filename='ssh.log', level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
def execute_command(hostname, port, username, password, command):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, port=port, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command(command)
output = stdout.read().decode()
if stderr:
logging.error(f'在 {hostname} 上执行命令时出错: {stderr.read().decode()}')
ssh.close()
return output
except Exception as e:
logging.error(f'连接 {hostname} 时出错: {str(e)}')
# 服务器信息列表
server_list = [
{'hostname': '192.168.1.1', 'port': 22, 'username': 'root', 'password': '123456'},
{'hostname': '192.168.1.2', 'port': 22, 'username': 'root', 'password': 'password123'},
{'hostname': '192.168.1.3', 'port': 22, 'username': 'root', 'password': 'password123'},
]
# 执行命令
command = '你需要执行的命令'
for server in server_list:
execute_command(server['hostname'], server['port'], server['username'], server['password'], command)
你也可以记录output看看返回了什么,有时候是空就意味着没有报错,具体的自己修改吧