日期:2014-05-16  浏览次数:20761 次

[同步][Python]同步两台Linux PC上的安装软件

原文地址:http://nourlcn.ownlinux.net/2011/10/sync-soft-on-two-machines.html


写了个脚本,可以同步两台linux pc上安装的软件。

需求:我最常用的两台pc装的都使ubuntu11.04, 一台在实验室,一台在公司,都处于内网中,互相不能访问。两台机器都有开发的需要,因此最好能安装相同的软件环境。

因此写了个脚本,通过dpkg -l > file,将file通过ubuntu one云存储服务同步,运行这个python脚本,设置好file的路径,可以安装remote机器上得deb包,卸载local机器上多余的deb包。

工具很简单,一看就明白,可能有bug,欢迎提出。


代码托管在 https://github.com/Nourl/tools/blob/master/sync_soft.py
本博客订阅地址:http://feeds.feedburner.com/nourlcn


?

#!/usr/bin/env python
#encode:utf-8

import re
import os

def get_soft_list(fobject):
    list = []
    i = 0
    r = re.compile('[a-z0-9+-\.]+')
    

    for line in fobject:
	    if i < 1 and line[:2] == "ii":
		    #line = list(line)
		    #print type(line) #str
		    #print len(line)
		    print line
            i += 1
            m = r.match(line[4:])
            if m:
                #print m.group()
                list.append(m.group())
    #print list,len(list)
    return list

def install_soft(local,remote):
    for x in remote:
        if x in local:
            pass
        else:
            print x,"is not installed\n"
            cmd = "aptitude install " + x 
            os.system(cmd)
            
def remove_soft(local,remote):
    for x in local:
        if x in remote:
            pass
        else:
            print x," will be removed\n"
            cmd = "aptitude remove " + x 
            os.system(cmd)
    os.system('aptitude autoremove')
    os.system('aptitude autoclean')
    



if __name__ == "__main__":
    fin = file('/home/nourl/install.soft','r')
    remote_list = get_soft_list(fin)
    fin.close()    
    
    #print local_list
    install = raw_input("install remote machine soft?")
    if install:
        #print len(soft_list)
        os.popen('dpkg -l > tmp_local_soft')
        flocal = file('tmp_local_soft','r')
        local_list = get_soft_list(flocal)
        flocal.close()
        install_soft(local_list, remote_list)
        
#    remove = raw_input("remove local machine soft?")
#    if remove:
#        #print len(soft_list)
#        os.popen('dpkg -l > tmp_local_soft')
#        flocal = file('tmp_local_soft','r')
#        local_list = get_soft_list(flocal)
#        flocal.close()
#        remove_soft(local_list, remote_list)
#        
#    if install or remove:
#        os.system('rm tmp_local_soft')
    if install:
        os.system('rm tmp_local_soft')
        
    print "Done!\n Soft on your system is the same as remote machine~!\n"

?