环境:Linux
脚本:Python
功能:批量IP,远程执行命令、拷贝文件
运行:./ssh_scp.py iplist.txt
脚本内容:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paramiko
import string
import sys
host_file = sys.argv[1]
username = ‘root‘
password = [email protected]
port = 22
paramiko.util.log_to_file(‘syslogin.log‘)
# 命令列表
cmd_list1 = [‘mkdir -pv /usr/local/zabbix/scripts/tmp‘]
cmd_list2 = [‘usermod -a -G mysql zabbix‘,‘chmod 755 /usr/local/zabbix/scripts‘]
#本地/远程机器 绝对路径文件名
localpath1 = "/data/file1"
remotpath1 = "/data/file1"
# 定义ssh函数
def SSH_CMD(hostname,cmds):
try:
for cmd in cmds:
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=username, password=password)
for cmd in cmds:
stdin,stdout,stderr = ssh.exec_command("%s" % cmd)
print stdout.read()
ssh.close()
except Exception, e:
print str(e)
#定义scp函数
def SCP_FILE(hostname):
try:
t = paramiko.Transport((hostname, port))
t.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(localpath1, remotpath1)
print "%s" % localpath1
except Exception, e:
print str(e)
if __name__ == ‘__main__‘:
with open(host_file) as f:
for ip in f.readlines():
ip = ip.strip(‘\n‘)
hostname = "%s" % ip
print "IP : %s" % ip
SSH_CMD(hostname,cmd_list1)
print "xxxxxx ssh ok "
SCP_FILE(hostname)
print "scp xxxx ok"
--OK
原文:http://www.cnblogs.com/cuisi/p/6561208.html