免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3843 | 回复: 7
打印 上一主题 下一主题

系统管理脚本_向多台服务器传输文件 [复制链接]

论坛徽章:
2
2015年迎新春徽章
日期:2015-03-04 09:55:28IT运维版块每日发帖之星
日期:2016-07-29 06:20:00
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-03-29 19:37 |只看该作者 |倒序浏览
本帖最后由 ning_lianjie 于 2012-09-19 22:04 编辑

增加了主机检测函数 socket_host,避免定义了不存在的主机,或者主机名错误,导致脚本退出.
代码如下:
  1. #!/usr/bin/env python
  2. #-*- coding: UTF-8 -*-
  3. # author:
  4. # changetime: 20120329

  5. import pexpect
  6. import getpass, os
  7. import sys, getopt
  8. import socket
  9. import traceback
  10. from ConfigParser import ConfigParser

  11. def usage():
  12.     print '\nUsage: qrsync.py '
  13.     print '编辑.list配置文件'
  14.     sys.exit(0)

  15. def rsync_input():
  16.     try:
  17.         #files    = raw_input('Flies: ')
  18.         #hosts    = raw_input('Hostname: ')
  19.         #hosts = 'hostname'
  20.         #user     = raw_input('User: ')
  21.         #user = 'lianjie.ning'
  22.         password      = getpass.getpass('Please enter password: ')
  23.     except:
  24.         print '\nERROR: input error,please try agent run script\n'
  25.         usage()
  26.     return password

  27. def load_config():
  28.     cfg_path = os.path.join(os.environ["HOME"], "bin/qrsync.list")
  29.     cfg_temp = '''[connects]
  30. user   =
  31. hosts  =
  32. # 跳板机存放authorized_keys文件,用ssh登录仍然需要输入token密码
  33. # 但是应用rsync命令,则可以直接传送.
  34. files  =
  35. rpath  =
  36. '''
  37.     #将cfg_temp写入文件
  38.     # user 用户
  39.     # hosts 将要传输文件的远程主机列表
  40.     # files 需要传输的文件
  41.     # rpath 远程主机的目录,传输的用户要有写入权限.
  42.     if not os.path.exists(cfg_path):
  43.         open(cfg_path, 'w').write(cfg_temp)
  44.         #加载stat模块,修改文件属性.
  45.         #os.chmod(cfg_path, stat.S_IREAD)
  46.     cfg = ConfigParser()
  47.     cfg.read(cfg_path)
  48.     user   = cfg.get('connects', 'user')
  49.     hosts  = cfg.get('connects', 'hosts')
  50.     files  = cfg.get('connects', 'files')
  51.     rpath  = cfg.get('connects', 'rpath')
  52.     return (user,hosts,files,rpath)

  53. # 检测列表中的主机
  54. def socket_host(host):
  55.     try:
  56.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  57.         sock.settimeout(3)
  58.         sock.connect((host, 22))
  59.         sock.close()
  60.         return 0
  61.     except:
  62.         print 'ping: unknown host %s' % (host)
  63.         return 1
  64.         #sys.exit(0)   

  65. def rsync_core(user, host, files, rpath, password):
  66.     #password = rsync_input()
  67.     #print command
  68.     #print 'exec command: /usr/bin/rsync -tvzrpc %s %s@hostname:.ssh/' % (files, user)
  69.     #print host
  70.     #check = raw_input('Are you sure transmitted to the tools(yes/no): ')
  71.     check = 'yes'
  72.     if check == 'yes':
  73.         rsync_newkey = 'Are you sure you want to continue connecting'
  74.         child = pexpect.spawn('/usr/bin/rsync -tvzrpc %s %s@%s:%s' % (files, user, host, rpath))
  75.         try:
  76.             i = child.expect([pexpect.TIMEOUT, rsync_newkey, 'password: ', "id_rsa': "])
  77.         except:
  78.             print '出现问题的原因:'
  79.             print '1.该主机不存在'
  80.             print '2.命令不需要交互,请检查主机直接是否做了授信'
  81.             print 'please checkout host and host...'
  82.             sys.exit(0)
  83.         if i == 0: # Timeout
  84.             print 'ERROR!'
  85.             print child.before, child.after
  86.             return None
  87.         if i == 1: # SSH does not have the public key. Just accept it.
  88.             child.sendline ('yes')
  89.             child.expect ('password: ')
  90.             i = child.expect([pexpect.TIMEOUT, 'password: '])
  91.             if i == 0: # Timeout
  92.                 print 'ERROR!'
  93.                 print child.before, child.after
  94.                 return None      
  95.         child.sendline(password)
  96.         child.expect(pexpect.EOF)
  97.         print child.before   # Print the result of the command
  98.         print child.after
  99.     else:
  100.         sys.exit(0)

  101. def main():
  102.     # 读取密码文件
  103.     password = rsync_input()
  104.     # load file
  105.     (user,hosts,files,rpath) = load_config()
  106.     if user == None:
  107.         sys.exit(0)
  108.     # print user, password
  109.     filter_hosts = []
  110.     hosts = hosts.strip().split(' ')
  111.     for host in hosts:
  112.         print host
  113.         i = socket_host(host)
  114.         if i == 0:
  115.             #print '111'
  116.             filter_hosts.append(host)
  117.         else:
  118.             #print '222'
  119.             pass
  120.     #for i in filter_hosts:
  121.         #print i
  122.     #sys.exit(0)
  123.     for i,host in enumerate(filter_hosts):
  124.         print i,"rsync -tvzrp %s %s@%s:%s" % (files,user,host,rpath)
  125.     #sys.exit(0)
  126.    
  127.     #确认   
  128.     check = raw_input('Are you sure transmitted to the host(yes/no): ')
  129.     if check == 'yes':
  130.         for i,host in enumerate(hosts):
  131.             rsync_core(user, host, files, rpath, password)
  132.             print i,host
  133.     else:
  134.         sys.exit(0)

  135. if __name__ == '__main__':
  136.     try:
  137.         main()
  138.     except Exception, e:
  139.         print str(e)
  140.         traceback.print_exc()
  141.         os._exit(1)
复制代码

论坛徽章:
0
2 [报告]
发表于 2012-04-06 11:36 |只看该作者
如果只是查看端口22是不是通的话
用paramiko模块的sshclient即可

论坛徽章:
0
3 [报告]
发表于 2012-04-06 13:02 |只看该作者
回复 2# Gray1982

本质还是用的socket
   

论坛徽章:
0
4 [报告]
发表于 2012-04-06 14:09 |只看该作者
基本的都是用socket,所以这是最底层的
用paramiko不是简洁一些嘛

论坛徽章:
2
2015年迎新春徽章
日期:2015-03-04 09:55:28IT运维版块每日发帖之星
日期:2016-07-29 06:20:00
5 [报告]
发表于 2012-04-06 22:36 |只看该作者
回复 4# Gray1982
socket 检测,需要端口的,我想用ping检测,不知有和指教?

   

论坛徽章:
2
2015年迎新春徽章
日期:2015-03-04 09:55:28IT运维版块每日发帖之星
日期:2016-07-29 06:20:00
6 [报告]
发表于 2012-04-06 22:38 |只看该作者
回复 2# Gray1982

回头我研究一下paramiko,这个模块
   

论坛徽章:
0
7 [报告]
发表于 2012-04-08 20:01 |只看该作者
回复 5# ning_lianjie


    ping如果你查网络通不通还行,不过前提是对方没有禁ping。现在一些服务器和硬件设备在安全程度上来说大部分已经禁ping。
如果想看SSH通不通,调用系统命令可以,比如nc。我因为用Python写的,所以就直接用Paramiko模块了,这个很简单,一看就会

论坛徽章:
0
8 [报告]
发表于 2012-04-12 20:27 |只看该作者
pingaling = os.popen("ping -n 1 -w 2 " + ip)
        while True:
            line = pingaling.readline()
            if not line: break
            igot = re.findall(lifeline, line)
            if igot:
                print "Host %s is alive" % ip
                ConnIPC(ip)
#                fp.write("%s\n" % ip)
                break
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP