4. 批量远程密码连接
- from paramiko.ssh_exception import NoValidConnectionsError
- from paramiko.ssh_exception import AuthenticationException
- def connect(cmd,hostname,port=22,username='root',passwd='westos'):
- import paramiko
- ##1.创建一个ssh对象
- client = paramiko.SSHClient()
- #2.解决问题:如果之前没有,连接过的ip,会出现选择yes或者no的操作,
- ##自动选择yes
- client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- #3.连接服务器
- try:
- client.connect(hostnamehostname=hostname,
- portport=port,
- usernameusername=username,
- password=passwd)
- print('正在连接主机%s......'%(hostname))
- except NoValidConnectionsError as e: ###用户不存在时的报错
- print("连接失败")
- except AuthenticationException as t: ##密码错误的报错
- print('密码错误')
- else:
- #4.执行操作
- stdin,stdout, stderr = client.exec_command(cmd)
- #5.获取命令执行的结果
- result=stdout.read().decode('utf-8')
- print(result)
- #6.关闭连接
- finally:
- client.close()
- with open('ip.txt') as f: #ip.txt为本地局域网内的一些用户信息
- for line in f:
- lineline = line.strip() ##去掉换行符
- hostname,port,username,passwd= line.split(':')
- print(hostname.center(50,'*'))
- connect('uname', hostname, port,username,passwd)
5. paramiko基于公钥密钥连接
- import paramiko
- from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
- def connect(cmd, hostname, port=22, user='root'):
- client = paramiko.SSHClient()
- private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
- ###id_rsa为本地局域网密钥文件
- client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- try:
- client.connect(hostnamehostname=hostname,
- portport=port,
- userusername=user,
- pkey=private_key
- )
- stdin, stdout, stderr = client.exec_command(cmd)
- except NoValidConnectionsError as e:
- print("连接失败")
- except AuthenticationException as e:
- print("密码错误")
- else:
- result = stdout.read().decode('utf-8')
- print(result)
- finally:
- client.close()
- for count in range(254):
- host = '172.25.254.%s' %(count+1)
- print(host.center(50, '*'))
- connect('uname', host)
6. 基于密钥的上传和下载
- import paramiko
- private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
- tran = paramiko.Transport('172.25.254.31',22)
- tran.connect(username='root',password='westos')
- #获取SFTP实例
- sftp = paramiko.SFTPClient.from_transport(tran)
- remotepath='/home/kiosk/Desktop/fish8'
- localpath='/home/kiosk/Desktop/fish1'
- sftp.put(localpath,remotepath)
- sftp.get(remotepath, localpath)
(编辑:ASP站长网)
|