def main(): logo = """ _ _ ____ _ _ __| |__ ____ ____ | | / _ \| | | |\_ _// _ \/ _ \| | | |_| | |_| | | |_.| |_| | |_| | |__. | ___/ \__. | \___/ \___/ \___/\____/ |_| |___/ """ colorprint.color_print(logo, 'pink') colorprint.color_print( " --- Mark's Python toolkit since 2015 --- \n", 'skyblue') menu = '-' * 60 + '\n' + """ [1] externalip: Get external IP of your computer [2] scanmyport: Scan some important port of your computer [3] synchronize: Synchronnize files to removable disk [4] zipbackup: Zip Backup [5] createhtml5: Create a basic HTML5 template file [6] md5sha: .exe MD5、SHA-1、SHA-256、SHA-512 [7] countdokupages: count doku pages [8] synmusic: Synchronnize music files to SD card [x] exit: Exit """ + '\n' + '-' * 60 colorprint.color_print(menu, 'yellow') while True: command = input(">>") if command == "exit" or command == "x": colorprint.color_print('Byebye!', 'pink') break elif command == "h": colorprint.color_print(menu, 'yellow') else: process_command(command)
def process_command(cmd): try: if len(re.findall(r'^\d+$', cmd)) > 0: eval('c' + cmd)() else: eval(cmd)() except: colorprint.color_print('Wrong command', 'red')
def _clearbackup(ori_dir,aim_dir): os.chdir(aim_dir)# Changes the current working directory to aim directory listdir = os.listdir() for name in listdir:# Directory traversal if os.path.isfile(aim_dir+'\\'+name): # If file if not os.path.exists(ori_dir+'\\'+name): # If the file not exsit on origin repository os.remove(aim_dir+'\\'+name) # Remove this file colorprint.color_print('Backup repository deleted file:' + aim_dir+'\\'+name,'red') elif os.path.isdir(aim_dir+'\\'+name):# If directory pass
def udpscan(ports, address): with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: for port in ports: try: s.sendto(b'Hello', ('127.0.0.1', port)) data = s.recv(1024) colorprint.color_print( '{} Open - {}'.format(port, ports[port]), 'red') except: colorprint.color_print( '{} Close - {}'.format(port, ports[port]), 'green') s.close()
def _countpages(aim_dir): global dokupages os.chdir( aim_dir) # Changes the current working directory to orginal directory listdir = os.listdir() for name in listdir: # Directory traversal if len(re.findall(r'\.txt$', name)) > 0: dokupages = dokupages + 1 colorprint.color_print( str(dokupages) + ':' + aim_dir + '\\' + name, 'skyblue') continue if os.path.isdir(aim_dir + '\\' + name): # If directory _countpages(aim_dir + '\\' + name) # Recursion/递归
def tcpscan(ports, address): with socket.socket( socket.AF_INET, socket.SOCK_STREAM ) as s: #Create a socket, AF_INET for IPv4,AF_INET6 for IPv6 for port in ports: try: s.connect((address, port)) colorprint.color_print( '{} Open - {}'.format(port, ports[port]), 'red') except: colorprint.color_print( '{} Close - {}'.format(port, ports[port]), 'green') s.close() #Close network connect
def createhtml5(): information = dict(title=None, filename=None, path=None) while True: try: colorprint.color_print("\n Begin to create a HTML5 file\n", 'yellow') populate_information(information) _create_html_file(**information) except ValueError as err: colorprint.color_print("Task canceled: %s\n" % err, 'red') if (_get_string("\nCreate another one(y/n)?", default="n").lower() not in {"y", "yes"}): break
def zipbackup(): avaiabel_drives = _getDrives() avaiabel_drives_lens = len(avaiabel_drives) if avaiabel_drives_lens == 1: removable_disk_volume = avaiabel_drives[0] elif avaiabel_drives_lens == 0: colorprint.color_print('Please connect the data cable and retry!', 'red') return else: colorprint.color_print( 'Please choose the volume serial number of your removable disk:(Current avaiable drives:' + ','.join(avaiabel_drives) + ')', 'yellow') removable_disk_volume = input(">>") zipfilename = removable_disk_volume + ":\\zipbackup\\" + time.strftime( '%Y-%m-%d') + ".zip" folders_to_zip = [ "C:\\Users\\Mark\\OneDrive\\design", "C:\\markli\\github", "C:\\Users\\Mark\\OneDrive\\time" ] f = zipfile.ZipFile(zipfilename, 'w', zipfile.ZIP_DEFLATED) for folder in folders_to_zip: colorprint.color_print("processing: " + folder, 'yellow') for dirpath, dirnames, filenames in os.walk(folder): if re.search(r'\\\.git', dirpath): #fitler .git folder continue for filename in filenames: f.write(os.path.join(dirpath, filename)) f.close() colorprint.color_print('Zip completed', 'pink')
def scanmyport(): address = '127.0.0.1' tcpports = { 80: 'HTTP', 135: 'RPC(远程过程调用)服务', 139: '获得NetBIOS/SMB服务-文件和打印机共享', 445: '在局域网中访问共享文件夹或共享打印机', 593: '#', 2745: '#', 3127: '#', 6129: '远程控制软件(dameware nt utilities)服务端监听端口', 3389: '远程桌面' } udpports = { 135: 'RPC(远程过程调用)服务', 137: '在局域网中提供计算机的名字或IP地址查询服务,一般安装了NetBIOS协议后,该端口会自动处于开放状态', 138: '端口的主要作用就是提供NetBIOS环境下的计算机名浏览功能', 139: '获得NetBIOS/SMB服务-文件和打印机共享', 445: '在局域网中访问共享文件夹或共享打印机' } colorprint.color_print('-' * 50, 'yellow') colorprint.color_print('TCP:', 'yellow') tcpscan(tcpports, address) colorprint.color_print('UDP:', 'yellow') udpscan(udpports, address) colorprint.color_print('-' * 50, 'yellow')
def _create_html_file(title, filename, path): title = xml.sax.saxutils.escape(title) html = HTML_TEMPLATE.format(**locals()) #begin to save fh = None try: fh = open(path + filename, "w", encoding="utf8") fh.write(html) except EnvironmentError as err: colorprint.color_print("Error:%s\n" % err, 'red') else: colorprint.color_print("Save file%s\n" % filename, 'skyblue') finally: if fh is not None: fh.close()
def _get_string(message, name="string", default=None, minimum_length=0, maximum_length=80): message += ":" if default is None else "[{0}]:".format(default) while True: try: line = input(message) if not line: if default is not None: return default if minimum_length == 0: return "" else: raise ValueError("{0} may not be empty".format(name)) if not (minimum_length <= len(line) <= maximum_length): raise ValueError( "{name} must have at least" "{minimum_length} and at most" "{maximum_length} chararcters".format(**locals())) return line except ValueError as err: colorprint.color_print("ERROR:%s\n" % err, 'red')
def externalip(): url = 'http://www.ip138.com/ips1388.asp' req = urllib.request.Request(url) response = urllib.request.urlopen(req) the_page = response.read().decode('gbk', 'ignore') result = re.findall(r'<td align="center">您的IP地址是:(.*)<br/><br/></td>', the_page) colorprint.color_print('-' * 50, 'yellow') colorprint.color_print('Your external IP:' + result[0], 'yellow') colorprint.color_print('-' * 50, 'yellow')
def synmusic(): avaiabel_drives=_getDrives() avaiabel_drives_lens = len(avaiabel_drives) if avaiabel_drives_lens == 1: removable_disk_volume = avaiabel_drives[0] elif avaiabel_drives_lens == 0: colorprint.color_print('Please connect the data cable and retry!','red') return else: colorprint.color_print('Please choose the volume serial number of your removable disk:(Current avaiable drives:'+','.join(avaiabel_drives)+')','yellow') removable_disk_volume = input(">>") backdir=['C:\\Users\\Mark\\OneDrive\\music',removable_disk_volume+':\\'] _clearbackup(backdir[0],backdir[1]) _syncbackup(backdir[0],backdir[1]) colorprint.color_print('Synchronnize completed!','pink')
def _syncbackup(ori_dir,aim_dir): os.chdir(ori_dir) # Changes the current working directory to orginal directory listdir = os.listdir() for name in listdir: # Directory traversal if len(re.findall(r'\.swo$',name))>0 or len(re.findall(r'\.swp$',name))>0 or len(re.findall(r'~$',name))>0 or name =='Thumbs.db': continue if os.path.isfile(ori_dir+'\\'+name):# If file if not os.path.exists(aim_dir+'\\'+name):# If backup repository don't have this file shutil.copy2(ori_dir+'\\'+name, aim_dir+'\\'+name) # Backup this file colorprint.color_print('Backup repository added new file:' + aim_dir+'\\'+name,'skyblue') elif os.path.getmtime(ori_dir+'\\'+name) != os.path.getmtime(aim_dir+'\\'+name):# If the modified date of this file are not the same than aim file shutil.copy2(ori_dir+'\\'+name, aim_dir+'\\'+name) # update this file colorprint.color_print('Backup repository updated file:' + aim_dir+'\\'+name,'yellow') elif os.path.isdir(ori_dir+'\\'+name):# If directory if not os.path.exists(aim_dir+'\\'+name):# If backup repository don't have this directory os.makedirs(aim_dir+'\\'+name) # Create this directory colorprint.color_print('Backup repository added new directory:'+aim_dir+'\\'+name,'pink') _syncbackup(ori_dir+'\\'+name,aim_dir+'\\'+name) # Recursion/递归
def countdokupages(): global dokupages dokupagedir = 'C:\\markli\\tool\\markbuild\\doku\\data\\pages' _countpages(dokupagedir) colorprint.color_print('Total:' + str(dokupages) + ' pages', 'pink')