paramiko的ssh与vsftp示例

2023-10-14 15:48
文章标签 示例 ssh paramiko vsftp

本文主要是介绍paramiko的ssh与vsftp示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

我已验证的示例:

 

def paramiko_ssh():host = "123.56.14.5"port = 22client = paramiko.SSHClient()client.load_system_host_keys()client.set_missing_host_key_policy(paramiko.client.WarningPolicy())try:client.connect(host, port, username='root', password='xxx', timeout=30)except Exception as e:print(e)stdin, stdout, stderr = client.exec_command('ls /opt')for line in stdout:print('... ' + line.strip('\n'))client.close()def paramiko_key():try:k = paramiko.RSAKey.from_private_key_file("~/.ssh/id_rsa")client = paramiko.SSHClient()client.set_missing_host_key_policy(paramiko.AutoAddPolicy())client.connect(hostname="123.56.14.5", username="root", pkey=k)stdin, stdout, stderr = client.exec_command('ls /opt')for line in stdout:print('... ' + line.strip('\n'))except Exception as e:print(e)finally:client.close()

 

pexpect代码示例     

#!/usr/bin/python
# encoding=utf-8
# Filename: pexpect_test.py
import pexpect
defsshCmd(ip, passwd, cmd):ret = -1ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))try:i = ssh.expect(['password:', 'continue connecting(yes/no)?'], timeout=5)if i == 0:ssh.sendline(passwd)elif i == 1:ssh.sendline('yes\n')ssh.expect('password:')ssh.sendline(passwd)ssh.sendline(cmd)r = ssh.read()print rret = 0except pexpect.EOF:print "EOF"ret = -1except pexpect.TIMEOUT:print "TIMEOUT"ret = -2finally:ssh.close()return retsshCmd('xxx.xxx.xxx.xxx','xxxxxx','ls /root')

paramiko代码示例

注意:必须要增加client.load_system_host_keys()此句,否则报如下错误:

unbound method missing_host_key() must be called with AutoAddPolicy instance as first argument (got SSHClient instance instead)

#!/usr/bin/python
# encoding=utf-8
# Filename: paramiko_test.py
import datetime
import threading
import paramikodefsshCmd(ip, username, passwd, cmds):try:client = paramiko.SSHClient()client.load_system_host_keys()client.set_missing_host_key_policy(paramiko.AutoAddPolicy)client.connect(ip, 22, username, passwd, timeout=5)for cmd in cmds:stdin, stdout, stderr = client.exec_command(cmd)lines = stdout.readlines()# print outfor line in lines:print line,print '%s\t 运行完毕\r\n' % (ip)except Exception, e:print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)finally:client.close()#上传文件       
defuploadFile(ip,username,passwd):try:t=paramiko.Transport((ip,22))t.connect(username=username,password=passwd)sftp=paramiko.SFTPClient.from_transport(t)remotepath='/root/main.py'localpath='/home/data/javawork/pythontest/src/main.py'sftp.put(localpath,remotepath)print '上传文件成功'except Exception, e:print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)finally:t.close()#下载文件 
defdownloadFile(ip,username,passwd):try:t=paramiko.Transport((ip,22))t.connect(username=username,password=passwd)sftp=paramiko.SFTPClient.from_transport(t)remotepath='/root/storm-0.9.0.1.zip'localpath='/home/data/javawork/pythontest/storm.zip'sftp.get(remotepath,localpath)print '下载文件成功'except Exception, e:print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)finally:t.close()  if __name__ == '__main__':# 需要执行的命令列表cmds = ['ls /root', 'ifconfig']# 需要进行远程监控的服务器列表servers = ['xxx.xxx.xxx.xxx']username = "root"passwd = "xxxxxx"threads = []print "程序开始运行%s" % datetime.datetime.now()# 每一台服务器创建一个线程处理for server in servers:th = threading.Thread(target=sshCmd, args=(server, username, passwd, cmds))th.start()threads.append(th)# 等待线程运行完毕for th in threads:th.join()print "程序结束运行%s" % datetime.datetime.now()#测试文件的上传与下载uploadFile(servers[0],username,passwd)downloadFile(servers[0],username,passwd)

 

Secure File Transfer Using SFTPClient

SFTPClient is used to open an sftp session across an open ssh Transport and do remote file operations.

An SSH Transport attaches to a stream (usually a socket), negotiates an encrypted session, authenticates, and then creates stream tunnels, called Channels, across the session. Multiple channels can be multiplexed across a single session (and often are, in the case of port forwardings).

 

以下是用密码认证功能登录的

#!/usr/bin/env python

import paramiko

 

socks=('127.0.0.1',22)

testssh=paramiko.Transport(socks)

testssh.connect(username='root',password='000000')

sftptest=paramiko.SFTPClient.from_transport(testssh)

remotepath="/tmp/a.log"

localpath="/tmp/c.log"

sftptest.put(remotepath,localpath)

sftptest.close()

testssh.close()

 

以下是用DSA认证登录的(PubkeyAuthentication)
#!/usr/bin/env python

import paramiko

 

serverHost = "192.168.1.172"

serverPort = 22

userName = "root"

keyFile = "/root/.ssh/zhuzhengjun"

known_host = "/root/.ssh/known_hosts"

channel = paramiko.SSHClient();

#host_keys = channel.load_system_host_keys(known_host)

channel.set_missing_host_key_policy(paramiko.AutoAddPolicy())

channel.connect(serverHost, serverPort,username=userName, key_filename=keyFile )

testssh=paramiko.Transport((serverHost,serverPort))

mykey = paramiko.DSSKey.from_private_key_file(keyFile,password='xyxyxy')

testssh.connect(username=userName,pkey=mykey)

sftptest=paramiko.SFTPClient.from_transport(testssh)

filepath='/tmp/e.log'

localpath='/tmp/a.log'

sftptest.put(localpath,filepath)

sftptest.close()

testssh.close()

 

以下是用RSA Key认证登录的

#!/usr/bin/evn python

 

import os

import paramiko

 

host='127.0.0.1'

port=22

testssh=paramiko.Transport((host,port))

privatekeyfile = os.path.expanduser('~/.ssh/badboy')

mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile,password='000000')

username = 'root'

testssh.connect(username=username, pkey=mykey)

sftptest=paramiko.SFTPClient.from_transport(testssh)

filepath='/tmp/e.log'

localpath='/tmp/a.log'

sftptest.put(localpath,filepath)

sftptest.close()

testssh.close()

 

另一种方法:

 

在paramiko中使用用户名和密码通过sftp传输文件,不使用key文件。

import getpass

import select

import socket

import traceback

import paramiko

def putfile():

    #import interactive

    # setup logging

    paramiko.util.log_to_file('demo.log')

    username = username

    hostname = hostname

    port = 22

    # now connect

    try:

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        sock.connect((hostname, port))

    except Exception, e:

        print '*** Connect failed: ' + str(e)

        traceback.print_exc()

        sys.exit(1)

    t = paramiko.Transport(sock)

    try:

        t.start_client()

    except paramiko.SSHException:

        print '*** SSH negotiation failed.'

        sys.exit(1)

    keys = {}

    # check server's host key -- this is important.

    key = t.get_remote_server_key()

    # get username

    t.auth_password(username, password)

    sftp = paramiko.SFTPClient.from_transport(t)

    # dirlist on remote host

    d=datetime.date.today()-datetime.timedelta(1)

    sftp.put(localFile,serverFile)

         sftp.close()

    t.close()

 

使用DSA认证登录的(PubkeyAuthentication)

 

#!/usr/bin/env python

 

import socket

import paramiko

import os

 

username='root'

hostname='192.168.1.169'

port = 22

 

sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((hostname, port))

 

t=paramiko.Transport(sock)

t.start_client()

key=t.get_remote_server_key()

#t.auth_password(username,'000000')

privatekeyfile = os.path.expanduser('/root/.ssh/zhuzhengjun')

mykey=paramiko.DSSKey.from_private_key_file(privatekeyfile,password='061128')

t.auth_publickey(username,mykey)

sftp=paramiko.SFTPClient.from_transport(t)

sftp.put("/tmp/a.log","/tmp/h.log")

sftp.close()

t.close()

 

使用RSA Key验证

#!/usr/bin/env python

 

import socket

import paramiko

import os

 

username='root'

hostname='127.0.0.1'

port = 22

 

sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((hostname, port))

 

t=paramiko.Transport(sock)

t.start_client()

key=t.get_remote_server_key()

#t.auth_password(username,'000000')

privatekeyfile = os.path.expanduser('~/.ssh/badboy')

mykey=paramiko.RSAKey.from_private_key_file(privatekeyfile,password='000000')

t.auth_publickey(username,mykey)

sftp=paramiko.SFTPClient.from_transport(t)

sftp.put("/tmp/a.log","/tmp/h.log")

sftp.close()

t.close()

 

这篇关于paramiko的ssh与vsftp示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/211500

相关文章

linux ssh如何实现增加访问端口

《linuxssh如何实现增加访问端口》Linux中SSH默认使用22端口,为了增强安全性或满足特定需求,可以通过修改SSH配置来增加或更改SSH访问端口,具体步骤包括修改SSH配置文件、增加或修改... 目录1. 修改 SSH 配置文件2. 增加或修改端口3. 保存并退出编辑器4. 更新防火墙规则使用uf

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java高效实现PowerPoint转PDF的示例详解

《Java高效实现PowerPoint转PDF的示例详解》在日常开发或办公场景中,经常需要将PowerPoint演示文稿(PPT/PPTX)转换为PDF,本文将介绍从基础转换到高级设置的多种用法,大家... 目录为什么要将 PowerPoint 转换为 PDF安装 Spire.Presentation fo

Python中isinstance()函数原理解释及详细用法示例

《Python中isinstance()函数原理解释及详细用法示例》isinstance()是Python内置的一个非常有用的函数,用于检查一个对象是否属于指定的类型或类型元组中的某一个类型,它是Py... 目录python中isinstance()函数原理解释及详细用法指南一、isinstance()函数

python中的高阶函数示例详解

《python中的高阶函数示例详解》在Python中,高阶函数是指接受函数作为参数或返回函数作为结果的函数,下面:本文主要介绍python中高阶函数的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录1.定义2.map函数3.filter函数4.reduce函数5.sorted函数6.自定义高阶函数

Vue实现路由守卫的示例代码

《Vue实现路由守卫的示例代码》Vue路由守卫是控制页面导航的钩子函数,主要用于鉴权、数据预加载等场景,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着... 目录一、概念二、类型三、实战一、概念路由守卫(Navigation Guards)本质上就是 在路

JAVA实现Token自动续期机制的示例代码

《JAVA实现Token自动续期机制的示例代码》本文主要介绍了JAVA实现Token自动续期机制的示例代码,通过动态调整会话生命周期平衡安全性与用户体验,解决固定有效期Token带来的风险与不便,感兴... 目录1. 固定有效期Token的内在局限性2. 自动续期机制:兼顾安全与体验的解决方案3. 总结PS

C#中通过Response.Headers设置自定义参数的代码示例

《C#中通过Response.Headers设置自定义参数的代码示例》:本文主要介绍C#中通过Response.Headers设置自定义响应头的方法,涵盖基础添加、安全校验、生产实践及调试技巧,强... 目录一、基础设置方法1. 直接添加自定义头2. 批量设置模式二、高级配置技巧1. 安全校验机制2. 类型

Python屏幕抓取和录制的详细代码示例

《Python屏幕抓取和录制的详细代码示例》随着现代计算机性能的提高和网络速度的加快,越来越多的用户需要对他们的屏幕进行录制,:本文主要介绍Python屏幕抓取和录制的相关资料,需要的朋友可以参考... 目录一、常用 python 屏幕抓取库二、pyautogui 截屏示例三、mss 高性能截图四、Pill

Java中的Schema校验技术与实践示例详解

《Java中的Schema校验技术与实践示例详解》本主题详细介绍了在Java环境下进行XMLSchema和JSONSchema校验的方法,包括使用JAXP、JAXB以及专门的JSON校验库等技术,本文... 目录1. XML和jsON的Schema校验概念1.1 XML和JSON校验的必要性1.2 Sche