1[Email protected] ~]#Cat passwd 2ROOT:X:0:0: root:/root:/bin/Bash3BIN:X:1:1: bin:/bin:/sbin/Nologin4DAEMON:X:2:2:d aemon:/sbin:/sbin/Nologin5ADM:X:3:4: adm:/var/adm:/sbin/Nologin6 LP: x:4:7:LP:/var/spool/lpd:/sbin/Nologin7 Sync: x:5:0:Sync:/sbin:/bin/Sync8SHUTDOWN:X:6:0: shutdown:/sbin:/sbin/shutdown9HALT:X:7:0: halt:/sbin:/sbin/HaltTen[[Email protected] ~]# One[[email protected] ~]# python5. pypasswd 0 1 A[[Email protected] ~]# -[Email protected] ~]#Cat passwd -ROOT:X:1:1: root:/root:/bin/Bash theBIN:X:1:1: bin:/bin:/sbin/Nologin -DAEMON:X:2:2:d aemon:/sbin:/sbin/Nologin -ADM:X:3:4: adm:/var/adm:/sbin/Nologin - LP: x:4:7:LP:/var/spool/lpd:/sbin/Nologin + Sync: x:5:1:Sync:/sbin:/bin/Sync -SHUTDOWN:X:6:1: shutdown:/sbin:/sbin/shutdown +HALT:X:7:1: halt:/sbin:/sbin/Halt A[[Email protected] ~]# at[[email protected] ~]# python5. pypasswd 1 2 passwd. New -[[Email protected] ~]# -[Email protected] ~]#Cat passwd -ROOT:X:1:1: root:/root:/bin/Bash -BIN:X:1:1: bin:/bin:/sbin/Nologin -DAEMON:X:2:2:d aemon:/sbin:/sbin/Nologin inADM:X:3:4: adm:/var/adm:/sbin/Nologin - LP: x:4:7:LP:/var/spool/lpd:/sbin/Nologin to Sync: x:5:1:Sync:/sbin:/bin/Sync +SHUTDOWN:X:6:1: shutdown:/sbin:/sbin/shutdown -HALT:X:7:1: halt:/sbin:/sbin/Halt the[[Email protected] ~]# *[Email protected] ~]#Cat passwd. New $ROOT:X:2:2: root:/root:/bin/BashPanax NotoginsengBIN:X:2:2: bin:/bin:/sbin/Nologin -DAEMON:X:2:2:d aemon:/sbin:/sbin/Nologin theADM:X:3:4: adm:/var/adm:/sbin/Nologin + LP: x:4:7:LP:/var/spool/lpd:/sbin/Nologin A Sync: x:5:2:Sync:/sbin:/bin/Sync theSHUTDOWN:X:6:2: shutdown:/sbin:/sbin/shutdown +HALT:X:7:2: halt:/sbin:/sbin/Halt -[[Email protected] ~]# $[[email protected] ~]# python5. pypasswdo $Parameter error: Python5. Py needs to edit the file to be replaced by the string of the string [saved as a file] -[[email protected] ~]# python5. PY PASSW1 2 - file does not exist the[Email protected] ~]#
The script code is as follows:
1 #!/usr/bin/python2 #-*-coding=utf-8-*-3 4 ImportSYS5 ImportOS6 7len_argv=Len (SYS.ARGV)8 #print ' Number of parameters ', Len_argv-19 Ten ifLEN_ARGV < 4: One Print 'parameter error: Python'+sys.argv[0]+'The file that needs to be edited is substituted by the string of the string [saved as a file]' A - elifLEN_ARGV > 5: - Print 'parameter error: Python'+sys.argv[0]+'The file that needs to be edited is substituted by the string of the string [saved as a file]' the - Else: - if notOs.path.isfile (sys.argv[1]): - Print 'file does not exist' + sys.exit () -S_file = File (Sys.argv[1],'r+') +Old_str = sys.argv[2] ANew_str = sys.argv[3] atD_file = File (sys.argv[1]+'. tmp','W') - forLineinchs_file.readlines (): - D_file.writelines (Line.replace (OLD_STR,NEW_STR)) - s_file.close () - d_file.close () - in ifLEN_ARGV = = 4: -Os.rename (sys.argv[1]+'. tmp', sys.argv[1]) to Else: +Os.rename (sys.argv[1]+'. tmp', Sys.argv[4])
Python applet, replacing a string in a file