Chinaunix首页 | 论坛 | 博客
  • 博客访问: 657868
  • 博文数量: 87
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2022
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-23 11:16
个人简介

西邮大三狗!!!

文章分类

全部博文(87)

文章存档

2015年(47)

2014年(40)

分类: Python/Ruby

2015-01-31 19:36:09

  1. 本机通过堡垒机(192.168.2.201)向目标主机(192.168.2.202)上传文件test.c
  2. __author__ = 'silence0607'
    #-*-coding:utf-8-*-
    #!/usr/bin/env python

    import paramiko,sys

    localpath = '/home/nick/c/test.c'
    remotepath = '/tmp/test.c'
    passinfo = '\'s password: '


    if __name__ =='__main__':
        t = paramiko.Transport(('192.168.2.201',22))
        t.connect(username = 'root',password = 'silence')
        sftp = paramiko.SFTPClient.from_transport(t)
        sftp.put(localpath,remotepath)
        sftp.close()

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname = '192.168.2.201',username = 'root',password = 'silence')
        channel = ssh.invoke_shell()
        channel.settimeout(10)

        buff = ''
        resp = ''
        channel.send('scp /tmp/test.c root@192.168.2.202:/mnt'+'\n')
        while not buff.endswith(passinfo):
            try:
                resp = channel.recv(9999)
            except Exception,e:
                print 'Error info:%s connection time.'%(str(e))
                channel.close()
                ssh.close()
                sys.exit()
            buff += resp
            if not buff.find('yes/no') == -1:
                channel.send('yes\n')
                buff = ''


        channel.send('silence'+'\n')


        buff = ''
        while not buff.endswith('# '):
            resp = channel.recv(9999)
            if not resp.find(passinfo) == -1:
                print 'Error info: Authentication failed.'
                channel.close()
                ssh.close()
                sys.exit()


            buff += resp
        print buff
        channel.close()
        ssh.close()
    运行结果如下:

  3. 代码参考《python自动化运维技术与最佳实践》
阅读(2575) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~