1、安装库
pip install paramiko
2、函数介绍
导入库
import paramiko
创建客户端
ssh = paramiko.SSHClient()
设置校验
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
连接登录
ssh.connect(‘192.168.xx.xx’, 22, ‘root’, ‘pwd’)
执行命令
stdin, stdout, stderr = ssh.exec_command(‘pwd’)
读取结果打印
str1 = stdout.read().decode(‘utf-8’)
print(str1)
关闭ssh客户端
ssh.close()
3、代码编写
import paramiko
ssh = paramiko.SSHClient()
def ssh_login(ip, port, username, passwd):
global ssh
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, passwd)
return
def ssh_exe_cmd(cmd):
global ssh
stdin, stdout, stderr = ssh.exec_command(cmd)
str1 = stdout.read().decode('utf-8')
print(str1)
return
def main():
ssh_login('192.168.73.176', 22, 'z', 'z')
ssh_exe_cmd('pwd')
ssh_exe_cmd('ifconfig')
ssh.close()
return
main()
4、执行结果
5、项目实战
需求:
测试远程主机ssh能登录多少ssh
import paramiko
import time
def ssh_login(ip, port, username, passwd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, passwd)
return
def test_ssh_login():
i = 0
while(1):
i = i + 1
print("登录个数:", i)
ssh_login('192.168.73.176', 22, 'z', 'z')
#time.sleep(0.01)
def main():
test_ssh_login()
return
main()