Python——遠程管理腳本(一)

前言:Python初學者。

腳本實現目的:

    通過一臺集中控制的服務器管理其他所有服務器。

    主要功能有:遠程執行命令、上傳文件、獲取文件

    此腳本只能實現同時管理一臺服務器,批量多進程管理多臺服務器需要與另一個腳本配合實現。

腳本思路:

    利用Python的paramiko模塊(初步思路來源於Python入門老師Alex)

腳本不足:

    不能實現多個文件或者目錄的傳輸

    執行命令時,當命令中有空格時必須使用 \ 轉義,否則會有報錯

    以上不足後期慢慢解決,畢竟腳本都是長出來的。

腳本內容:

#!/usr/bin/env python
# coding=UTF-8
#This script is use for host manage
#Create by eleven in 2014-06-01
#Last changed in 2014-06-09

import paramiko as PO
import sys,os,time,socket

help_info='''\
Options:
	cmd		Run command in remote host
	get		Download file from remote host
	put		Upload file to remote host
	host		Remote host ipaddress or hostname
	user		Remote host username
	key		Use ssh-key authentication
	password 	Use password authentication
	null		If use ssh-key,then password is null
	command		Run command
	filename1	Download filename or upload filename
	filename2	Local save filename or remote save filename
Example:
	%s cmd 10.0.0.1 test key null ifconfig
	%s get 10.0.0.1 test password 123 '/etc/network' '/tmp/network'\n ''' %(sys.argv[0],sys.argv[0])

error_info='''\
Usage: \033[31m%s [cmd|get|put] host user [key|password] 'PASSWORD|null' [command|filename1 filename2]\033[0m
Detail: \033[31m%s --help\033[0m\n ''' %(sys.argv[0],sys.argv[0])

if sys.argv[1] == '--help':
	print help_info
	sys.exit()
elif len(sys.argv) < 7:
	print error_info
	sys.exit()

host = sys.argv[2]
user = sys.argv[3]
atype = sys.argv[4]
password=sys.argv[5]
cmd=sys.argv[6]
keyfile=os.path.expanduser("~/.ssh/id_rsa")
mykey=PO.RSAKey.from_private_key_file(keyfile)
ssh=PO.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(PO.AutoAddPolicy())

def ssh_con():
	try:
		if atype == 'key':
			ssh.connect(host,22,user,pkey=mykey,timeout=3)	#authentication of key
		elif atype == 'password':
			ssh.connect(host,22,user,password=password,timeout=3)	#authentication of password
		else:
			print 'Wrong authentication !\n'
	except PO.AuthenticationException:
		print "Use '%s' connect to '%s' authentication fail !\n" %(user,host)	
		sys.exit()
	except:
		print "Use '%s' connect to '%s' fail !\n" %(user,host)	
		sys.exit()
		
	try:
		stdin,stdout,stderr=ssh.exec_command(cmd,timeout=10)
		out=stdout.read()
		errout=stderr.read()
		print '%s:' %host
		if errout:
			print errout
		elif out:
			print out
		else:
			print '\tCommand <%s> exec ok !'%cmd
	except socket.timeout:
		print "Command '%s' exec in '%s' timeout !\n"%(cmd,host)
	finally:
		ssh.close()

def sftp_get():			#get file in remote host
	try:
		t=PO.Transport((host,22))
		getfile=sys.argv[6]	#remote host filename
		localfile=sys.argv[7]	#save in localpath and rename
		if atype == 'key':
			t.connect(username=user,pkey=mykey)
		elif atype == 'password':
			t.connect(username=user,password=password)
		else:
			print 'Wrong authentication !\n'
		sftp = PO.SFTPClient.from_transport(t)
		sftp.get(getfile,localfile)
		print 'Host is: %s\nGetfile_Name is: %s\nLocalfile_Name is: %s\n' %(host,getfile,localfile)
	except socket.error:
		print "Can not connect to '%s'\n " %host
	except PO.AuthenticationException:
		print "Use '%s' connect to '%s' authentication fail !\n" %(user,host)	
	except IOError:
		print "Remote file '%s' does not exist !\n"%getfile
	finally:
		ssh.close()
		#t.close()

def sftp_put():			#put file to remote host
	try:
		t=PO.Transport((host,22))
		putfile=sys.argv[6]	#local file name
		remotefile=sys.argv[7]	#put in remote host path and rename
		if atype == 'key':
			t.connect(username=user,pkey=mykey)
		elif atype == 'password':
			t.connect(username=user,password=password)
		else:
			print 'Wrong authentication !\n'
		sftp = PO.SFTPClient.from_transport(t)
		sftp.put(putfile,remotefile)
		print 'Host is: %s\nPutfile_Name is: %s\nRemotefile_Name is: %s\n' %(host,putfile,remotefile)
	except socket.error:
		print "Can not connect to '%s'\n" %host
	except PO.AuthenticationException:
		print "Use '%s' connect to '%s' authentication fail !\n" %(user,host)	
	except OSError:
		print "Local file '%s' does not exist !\n"%putfile
	except IOError:
		print "Put file '%s' error,Maybe remote server permission denied !\n"%putfile
	finally:
		ssh.close()
		#t.close()

action=sys.argv[1]
if action == 'cmd':
	if len(sys.argv) == 7:
		ssh_con()
	else:
		print error_info
elif action == 'get':
	if len(sys.argv) == 8:
		sftp_get()
	else:
		print error_info
elif action == 'put':
	if len(sys.argv) == 8:
		sftp_put()
	else:
		print error_info
else:
	print 'Wrong action !\n'

   


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章