功能模块

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys,getopt
import os

def add(argv):
    hostip = ''
    username = ''
    password = ''
    try:
        opts, args = getopt.getopt(argv,"h:u:p:")
    except getopt.GetoptError:
        print 'ERROR: server.py add -h  -u  -p '
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-h":
            hostip = arg
        elif opt == "-u":
            username = arg
        elif opt == "-p":
            password = arg
    writeInfo(hostip,username,password)

def delete(argv):
    hostip = ''
    try:
        opts, args = getopt.getopt(argv,"h:")
    except getopt.GetoptError:
        print 'ERROR: server.py delete -h '
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-h":
            hostip = arg
    deleteInfo(hostip)

def listInfo():
    inputfile = open('/Users/ibunny/serverinfo','r')
    for line in inputfile:
        if line == '\n': pass
        else: print line.strip()
    inputfile.close()

def writeInfo(hostip, username, password):
    outputfile = open('/Users/ibunny/serverinfo','a')
    outputfile.write(hostip + ' ' + username + ' ' + password + '\n')
    outputfile.close()

def deleteInfo(hostip):
    inputfile = open('/Users/ibunny/serverinfo','r')
    outputfile = open('/Users/ibunny/serverinfo_new','w')
    for line in inputfile:
        if line.strip().split(" ")[0] == hostip:
            pass
        else:
            outputfile.write(line)
    inputfile.close()
    outputfile.close()
    os.remove('/Users/ibunny/serverinfo')
    os.rename('/Users/ibunny/serverinfo_new', '/Users/ibunny/serverinfo')



if __name__ == "__main__":
    option = sys.argv[1]
    if (option == 'add'):
        add(sys.argv[2:])
    elif (option == 'delete'):
        delete(sys.argv[2:])
    elif (option == 'list'):
        listInfo()
    else:
        print 'ERROR: only add/delete'





你可能感兴趣的:(功能模块)