import paramiko
def ssh_client_con():
"""创建ssh连接,并执行shell指令"""
# 1 创建ssh_client实例
ssh_client = paramiko.SSHClient()
# 自动处理第一次连接的yes或者no的问题
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
# port = '22'
# username = '用户名'
# password = ''
hostname = ['ip',]
# 2 连接服务器
for i in hostname:
print(i)
ssh_client.connect(
port=22,
hostname= 'ip',
username="用户名",
password="密码",
allow_agent=False,
look_for_keys=False
)
# 3 执行shell命令
# 构造shell指令
shell_command = """
display interface brief r
r
"""
# 执行shell指令
stdin, stdout, stderr = ssh_client.exec_command(shell_command)
# 输出返回信息
stdout_r = stdout.read()
print(stdout_r)
print(type(stdout_r))
# with open('host_site.txt', 'wb', ) as host_file:
# host_file.write(stdout_r)
# with open('host_site.txt', 'rb') as host_file:
# print((host_file.read()).decode("GB2312"))
if __name__ == '__main__':
ssh_client_con()