├── CountMillionCharacter.py ├── README.md ├── backup_automater_services.py ├── batch_file_rename.py ├── check_file.py ├── check_for_sqlite_files.py ├── check_internet_con.py ├── create_dir_if_not_there.py ├── daily_checks.py ├── dir_test.py ├── env_check.py ├── fileinfo.py ├── folder_size.py ├── get_info_remoute_srv.py ├── get_youtube_view.py ├── logs.py ├── merge.py ├── move_files_over_x_days.py ├── new_script.py ├── nmap_scan.py ├── nslookup_check.py ├── osinfo.py ├── password_cracker.py ├── ping_servers.py ├── ping_subnet.py ├── portscanner.py ├── powerdown_startup.py ├── powerup_checks.py ├── pscheck.py ├── puttylogs.py ├── recyclebin.py ├── script_count.py ├── script_listing.py ├── serial_scanner.py ├── sqlite_check.py ├── sqlite_table_check.py ├── testlines.py ├── webcam.py └── work_connect.py /CountMillionCharacter.py: -------------------------------------------------------------------------------- 1 | import pprint 2 | info = '''SCENE I. Yorkshire. Gaultree Forest. 3 | 4 | Enter the ARCHBISHOP OF YORK, MOWBRAY, LORD HASTINGS, and others 5 | ARCHBISHOP OF YORK 6 | What is this forest call'd? 7 | HASTINGS 8 | 'Tis Gaultree Forest, an't shall please your grace. 9 | ARCHBISHOP OF YORK 10 | Here stand, my lords; and send discoverers forth 11 | To know the numbers of our enemies. 12 | HASTINGS 13 | We have sent forth already. 14 | ARCHBISHOP OF YORK 15 | 'Tis well done. 16 | My friends and brethren in these great affairs, 17 | I must acquaint you that I have received 18 | New-dated letters from Northumberland; 19 | Their cold intent, tenor and substance, thus: 20 | Here doth he wish his person, with such powers 21 | As might hold sortance with his quality, 22 | The which he could not levy; whereupon 23 | He is retired, to ripe his growing fortunes, 24 | To Scotland: and concludes in hearty prayers 25 | That your attempts may overlive the hazard 26 | And fearful melting of their opposite. 27 | MOWBRAY 28 | Thus do the hopes we have in him touch ground 29 | And dash themselves to pieces. 30 | Enter a Messenger 31 | 32 | HASTINGS 33 | Now, what news? 34 | Messenger 35 | West of this forest, scarcely off a mile, 36 | In goodly form comes on the enemy; 37 | And, by the ground they hide, I judge their number 38 | Upon or near the rate of thirty thousand. 39 | MOWBRAY 40 | The just proportion that we gave them out 41 | Let us sway on and face them in the field. 42 | ARCHBISHOP OF YORK 43 | What well-appointed leader fronts us here? 44 | Enter WESTMORELAND 45 | 46 | MOWBRAY 47 | I think it is my Lord of Westmoreland. 48 | WESTMORELAND 49 | Health and fair greeting from our general, 50 | The prince, Lord John and Duke of Lancaster. 51 | ARCHBISHOP OF YORK 52 | Say on, my Lord of Westmoreland, in peace: 53 | What doth concern your coming? 54 | WESTMORELAND 55 | Then, my lord, 56 | Unto your grace do I in chief address 57 | The substance of my speech. If that rebellion 58 | Came like itself, in base and abject routs, 59 | Led on by bloody youth, guarded with rags, 60 | And countenanced by boys and beggary, 61 | I say, if damn'd commotion so appear'd, 62 | In his true, native and most proper shape, 63 | You, reverend father, and these noble lords 64 | Had not been here, to dress the ugly form 65 | Of base and bloody insurrection 66 | With your fair honours. You, lord archbishop, 67 | Whose see is by a civil peace maintained, 68 | Whose beard the silver hand of peace hath touch'd, 69 | Whose learning and good letters peace hath tutor'd, 70 | Whose white investments figure innocence, 71 | The dove and very blessed spirit of peace, 72 | Wherefore do you so ill translate ourself 73 | Out of the speech of peace that bears such grace, 74 | Into the harsh and boisterous tongue of war; 75 | Turning your books to graves, your ink to blood, 76 | Your pens to lances and your tongue divine 77 | To a trumpet and a point of war? 78 | ARCHBISHOP OF YORK 79 | Wherefore do I this? so the question stands. 80 | Briefly to this end: we are all diseased, 81 | And with our surfeiting and wanton hours 82 | Have brought ourselves into a burning fever, 83 | And we must bleed for it; of which disease 84 | Our late king, Richard, being infected, died. 85 | But, my most noble Lord of Westmoreland, 86 | I take not on me here as a physician, 87 | Nor do I as an enemy to peace 88 | Troop in the throngs of military men; 89 | But rather show awhile like fearful war, 90 | To diet rank minds sick of happiness 91 | And purge the obstructions which begin to stop 92 | Our very veins of life. Hear me more plainly. 93 | I have in equal balance justly weigh'd 94 | What wrongs our arms may do, what wrongs we suffer, 95 | And find our griefs heavier than our offences. 96 | We see which way the stream of time doth run, 97 | And are enforced from our most quiet there 98 | By the rough torrent of occasion; 99 | And have the summary of all our griefs, 100 | When time shall serve, to show in articles; 101 | Which long ere this we offer'd to the king, 102 | And might by no suit gain our audience: 103 | When we are wrong'd and would unfold our griefs, 104 | We are denied access unto his person 105 | Even by those men that most have done us wrong. 106 | The dangers of the days but newly gone, 107 | Whose memory is written on the earth 108 | With yet appearing blood, and the examples 109 | Of every minute's instance, present now, 110 | Hath put us in these ill-beseeming arms, 111 | Not to break peace or any branch of it, 112 | But to establish here a peace indeed, 113 | Concurring both in name and quality. 114 | WESTMORELAND 115 | When ever yet was your appeal denied? 116 | Wherein have you been galled by the king? 117 | What peer hath been suborn'd to grate on you, 118 | That you should seal this lawless bloody book 119 | Of forged rebellion with a seal divine 120 | And consecrate commotion's bitter edge? 121 | ARCHBISHOP OF YORK 122 | My brother general, the commonwealth, 123 | To brother born an household cruelty, 124 | I make my quarrel in particular. 125 | WESTMORELAND 126 | There is no need of any such redress; 127 | Or if there were, it not belongs to you. 128 | MOWBRAY 129 | Why not to him in part, and to us all 130 | That feel the bruises of the days before, 131 | And suffer the condition of these times 132 | To lay a heavy and unequal hand 133 | Upon our honours? 134 | WESTMORELAND 135 | O, my good Lord Mowbray, 136 | Construe the times to their necessities, 137 | And you shall say indeed, it is the time, 138 | And not the king, that doth you injuries. 139 | Yet for your part, it not appears to me 140 | Either from the king or in the present time 141 | That you should have an inch of any ground 142 | To build a grief on: were you not restored 143 | To all the Duke of Norfolk's signories, 144 | Your noble and right well remember'd father's? 145 | MOWBRAY 146 | What thing, in honour, had my father lost, 147 | That need to be revived and breathed in me? 148 | The king that loved him, as the state stood then, 149 | Was force perforce compell'd to banish him: 150 | And then that Harry Bolingbroke and he, 151 | Being mounted and both roused in their seats, 152 | Their neighing coursers daring of the spur, 153 | Their armed staves in charge, their beavers down, 154 | Their eyes of fire sparking through sights of steel 155 | And the loud trumpet blowing them together, 156 | Then, then, when there was nothing could have stay'd 157 | My father from the breast of Bolingbroke, 158 | O when the king did throw his warder down, 159 | His own life hung upon the staff he threw; 160 | Then threw he down himself and all their lives 161 | That by indictment and by dint of sword 162 | Have since miscarried under Bolingbroke. 163 | WESTMORELAND 164 | You speak, Lord Mowbray, now you know not what. 165 | The Earl of Hereford was reputed then 166 | In England the most valiant gentlemen: 167 | Who knows on whom fortune would then have smiled? 168 | But if your father had been victor there, 169 | He ne'er had borne it out of Coventry: 170 | For all the country in a general voice 171 | Cried hate upon him; and all their prayers and love 172 | Were set on Hereford, whom they doted on 173 | And bless'd and graced indeed, more than the king. 174 | But this is mere digression from my purpose. 175 | Here come I from our princely general 176 | To know your griefs; to tell you from his grace 177 | That he will give you audience; and wherein 178 | It shall appear that your demands are just, 179 | You shall enjoy them, every thing set off 180 | That might so much as think you enemies. 181 | MOWBRAY 182 | But he hath forced us to compel this offer; 183 | And it proceeds from policy, not love. 184 | WESTMORELAND 185 | Mowbray, you overween to take it so; 186 | This offer comes from mercy, not from fear: 187 | For, lo! within a ken our army lies, 188 | Upon mine honour, all too confident 189 | To give admittance to a thought of fear. 190 | Our battle is more full of names than yours, 191 | Our men more perfect in the use of arms, 192 | Our armour all as strong, our cause the best; 193 | Then reason will our heart should be as good 194 | Say you not then our offer is compell'd. 195 | MOWBRAY 196 | Well, by my will we shall admit no parley. 197 | WESTMORELAND 198 | That argues but the shame of your offence: 199 | A rotten case abides no handling. 200 | HASTINGS 201 | Hath the Prince John a full commission, 202 | In very ample virtue of his father, 203 | To hear and absolutely to determine 204 | Of what conditions we shall stand upon? 205 | WESTMORELAND 206 | That is intended in the general's name: 207 | I muse you make so slight a question. 208 | ARCHBISHOP OF YORK 209 | Then take, my Lord of Westmoreland, this schedule, 210 | For this contains our general grievances: 211 | Each several article herein redress'd, 212 | All members of our cause, both here and hence, 213 | That are insinew'd to this action, 214 | Acquitted by a true substantial form 215 | And present execution of our wills 216 | To us and to our purposes confined, 217 | We come within our awful banks again 218 | And knit our powers to the arm of peace. 219 | WESTMORELAND 220 | This will I show the general. Please you, lords, 221 | In sight of both our battles we may meet; 222 | And either end in peace, which God so frame! 223 | Or to the place of difference call the swords 224 | Which must decide it. 225 | ARCHBISHOP OF YORK 226 | My lord, we will do so. 227 | Exit WESTMORELAND 228 | 229 | MOWBRAY 230 | There is a thing within my bosom tells me 231 | That no conditions of our peace can stand. 232 | HASTINGS 233 | Fear you not that: if we can make our peace 234 | Upon such large terms and so absolute 235 | As our conditions shall consist upon, 236 | Our peace shall stand as firm as rocky mountains. 237 | MOWBRAY 238 | Yea, but our valuation shall be such 239 | That every slight and false-derived cause, 240 | Yea, every idle, nice and wanton reason 241 | Shall to the king taste of this action; 242 | That, were our royal faiths martyrs in love, 243 | We shall be winnow'd with so rough a wind 244 | That even our corn shall seem as light as chaff 245 | And good from bad find no partition. 246 | ARCHBISHOP OF YORK 247 | No, no, my lord. Note this; the king is weary 248 | Of dainty and such picking grievances: 249 | For he hath found to end one doubt by death 250 | Revives two greater in the heirs of life, 251 | And therefore will he wipe his tables clean 252 | And keep no tell-tale to his memory 253 | That may repeat and history his loss 254 | To new remembrance; for full well he knows 255 | He cannot so precisely weed this land 256 | As his misdoubts present occasion: 257 | His foes are so enrooted with his friends 258 | That, plucking to unfix an enemy, 259 | He doth unfasten so and shake a friend: 260 | So that this land, like an offensive wife 261 | That hath enraged him on to offer strokes, 262 | As he is striking, holds his infant up 263 | And hangs resolved correction in the arm 264 | That was uprear'd to execution. 265 | HASTINGS 266 | Besides, the king hath wasted all his rods 267 | On late offenders, that he now doth lack 268 | The very instruments of chastisement: 269 | So that his power, like to a fangless lion, 270 | May offer, but not hold. 271 | ARCHBISHOP OF YORK 272 | 'Tis very true: 273 | And therefore be assured, my good lord marshal, 274 | If we do now make our atonement well, 275 | Our peace will, like a broken limb united, 276 | Grow stronger for the breaking. 277 | MOWBRAY 278 | Be it so. 279 | Here is return'd my Lord of Westmoreland. 280 | Re-enter WESTMORELAND 281 | 282 | WESTMORELAND 283 | The prince is here at hand: pleaseth your lordship 284 | To meet his grace just distance 'tween our armies. 285 | MOWBRAY 286 | Your grace of York, in God's name then, set forward. 287 | ARCHBISHOP OF YORK 288 | Before, and greet his grace: my lord, we come. 289 | Exeunt''' 290 | count = { } 291 | for character in info.upper(): 292 | count.setdefault(character, 0) 293 | count[character] = count[character]+1 294 | 295 | value = pprint.pformat(count) 296 | print(value) 297 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Here is some more detailed information about the scripts I have written. I do not consider myself a programmer, I create these little programs as experiments to have a play with the language, or to solve a problem for myself. I would gladly accept pointers from others to improve the code and make it more efficient, or simplify the code. If you would like to make any comments then please feel free to email me at craig@geekcomputers.co.uk. 2 | 3 | In the scripts the comments etc are lined up correctly when they are viewed in [Notepad++](https://notepad-plus-plus.org/). This is what I use to code Python scripts. 4 | 5 | - `batch_file_rename.py` - This will batch rename a group of files in a given directory, once you pass the current and new extensions. 6 | 7 | - `create_dir_if_not_there.py` - Checks to see if a directory exists in the users home directory, if not then create it. 8 | 9 | - `dir_test.py` - Tests to see if the directory `testdir` exists, if not it will create the directory for you. 10 | 11 | - `env_check.py` - This script will check to see if all of the environment variables I require are set. 12 | 13 | - `fileinfo.py` - Show file information for a given file. 14 | 15 | - `folder_size.py` - This will scan the current directory and all subdirectories and display the size. 16 | 17 | - `logs.py` - This script will search for all `*.log` files in the given directory, zip them using the program you specify and then date stamp them. 18 | 19 | - `move_files_over_x_days.py` - This will move all the files from the source directory that are over 240 days old to the destination directory. 20 | 21 | - `nslookup_check.py` - This very simple script opens the file `server_list.txt` and the does an nslookup for each one to check the DNS entry. 22 | 23 | - `osinfo.py` - Displays some information about the OS you are running this script on. 24 | 25 | - `ping_servers.py` - This script will, depending on the arguments supplied will ping the servers associated with that application group. 26 | 27 | - `ping_subnet.py` - After supplying the first 3 octets it will scan the final range for available addresses. 28 | 29 | - `powerdown_startup.py` - This goes through the server list and pings the machine, if it's up it will load the putty session, if its not it will notify you. 30 | 31 | - `puttylogs.py` - This zips up all the logs in the given directory. 32 | 33 | - `script_count.py` - This scans my scripts directory and gives a count of the different types of scripts. 34 | 35 | - `script_listing.py` - This will list all the files in the given directory, it will also go through all the subdirectories as well. 36 | 37 | - `testlines.py` - This very simple script open a file and prints out 100 lines of whatever is set for the line variable. 38 | 39 | - `serial_scanner.py` contains a method called ListAvailablePorts which returns a list with the names of the serial ports that are in use in our computer, this method works only on Linux and Windows (can be extended for mac osx). If no port is found, an empty list is returned. 40 | 41 | - `get_youtube_view.py` - This is very simple python script to get more views for your youtube videos.Some times I use for repeating my favorite songs by this scripts. 42 | - `CountMillionCharacter.py` - This Script will,counting character script count how much character present *any text based file. 43 | -------------------------------------------------------------------------------- /backup_automater_services.py: -------------------------------------------------------------------------------- 1 | # Script Name : backup_automater_services.py 2 | # Author : Craig Richards 3 | # Created : 24th October 2012 4 | # Last Modified : 13th February 2016 5 | # Version : 1.0.1 6 | 7 | # Modifications : 1.0.1 - Tidy up the comments and syntax 8 | 9 | # Description : This will go through and backup all my automator services workflows 10 | 11 | import shutil # Load the library module 12 | import datetime # Load the library module 13 | import os # Load the library module 14 | 15 | today = datetime.date.today() # Get Today's date 16 | todaystr = today.isoformat() # Format it so we can use the format to create the directory 17 | 18 | confdir = os.getenv("my_config") # Set the variable by getting the value from the OS setting 19 | dropbox = os.getenv("dropbox") # Set the variable by getting the value from the OS setting 20 | conffile = ('services.conf') # Set the variable as the name of the configuration file 21 | conffilename = os.path.join(confdir, conffile) # Set the variable by combining the path and the file name 22 | sourcedir = os.path.expanduser('~/Library/Services/') # Source directory of where the scripts are located 23 | destdir = os.path.join(dropbox, "My_backups"+"/"+"Automater_services"+todaystr+"/") # Combine several settings to create 24 | 25 | # the destination backup directory 26 | for file_name in open(conffilename): # Walk through the configuration file 27 | fname = file_name.strip() # Strip out the blank lines from the configuration file 28 | if fname: # For the lines that are not blank 29 | sourcefile = os.path.join(sourcedir, fname) # Get the name of the source files to backup 30 | destfile = os.path.join(destdir, fname) # Get the name of the destination file names 31 | shutil.copytree(sourcefile, destfile) # Copy the directories 32 | -------------------------------------------------------------------------------- /batch_file_rename.py: -------------------------------------------------------------------------------- 1 | # batch_file_rename.py 2 | # Created: 6th August 2012 3 | 4 | ''' 5 | This will batch rename a group of files in a given directory, 6 | once you pass the current and new extensions 7 | ''' 8 | 9 | __author__ = 'Craig Richards' 10 | __version__ = '1.0' 11 | 12 | import os 13 | import sys 14 | 15 | 16 | def batch_rename(work_dir, old_ext, new_ext): 17 | ''' 18 | This will batch rename a group of files in a given directory, 19 | once you pass the current and new extensions 20 | ''' 21 | # files = os.listdir(work_dir) 22 | for filename in os.listdir(work_dir): 23 | # Get the file extension 24 | file_ext = os.path.splitext(filename)[1] 25 | # Start of the logic to check the file extensions, if old_ext = file_ext 26 | if old_ext == file_ext: 27 | # Set newfile to be the filename, replaced with the new extension 28 | newfile = filename.replace(old_ext, new_ext) 29 | # Write the files 30 | os.rename( 31 | os.path.join(work_dir, filename), 32 | os.path.join(work_dir, newfile) 33 | ) 34 | 35 | 36 | def main(): 37 | ''' 38 | This will be called if the script is directly invoked. 39 | ''' 40 | # Set the variable work_dir with the first argument passed 41 | work_dir = sys.argv[1] 42 | # Set the variable old_ext with the second argument passed 43 | old_ext = sys.argv[2] 44 | # Set the variable new_ext with the third argument passed 45 | new_ext = sys.argv[3] 46 | batch_rename(work_dir, old_ext, new_ext) 47 | 48 | 49 | if __name__ == '__main__': 50 | main() 51 | 52 | -------------------------------------------------------------------------------- /check_file.py: -------------------------------------------------------------------------------- 1 | # Script Name : check_file.py 2 | # Author : Craig Richards 3 | # Created : 20 May 2013 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : with statement added to ensure correct file closure 8 | 9 | # Description : Check a file exists and that we can read the file 10 | 11 | import sys # Import the Modules 12 | import os # Import the Modules 13 | 14 | # Readfile Functions which open the file that is passed to the script 15 | 16 | def readfile(filename): 17 | with open(filename, 'r') as f: # Ensure file is correctly closed under all circumstances 18 | line = f.read() 19 | print line 20 | 21 | def main(): 22 | if len(sys.argv) == 2: # Check the arguments passed to the script 23 | filename = sys.argv[1] # The filename is the first argument 24 | if not os.path.isfile(filename): # Check the File exists 25 | print '[-] ' + filename + ' does not exist.' 26 | exit(0) 27 | if not os.access(filename, os.R_OK): # Check you can read the file 28 | print '[-] ' + filename + ' access denied' 29 | exit(0) 30 | else: 31 | print '[-] Usage: ' + str(sys.argv[0]) + ' ' # Print usage if not all parameters passed/Checked 32 | exit(0) 33 | print '[+] Reading from : ' + filename # Display Message and read the file contents 34 | readfile(filename) 35 | 36 | if __name__ == '__main__': 37 | main() 38 | -------------------------------------------------------------------------------- /check_for_sqlite_files.py: -------------------------------------------------------------------------------- 1 | # Script Name : check_for_sqlite_files.py 2 | # Author : Craig Richards 3 | # Created : 07 June 2013 4 | # Last Modified : 14 February 2016 5 | # Version : 1.0.1 6 | 7 | # Modifications : 1.0.1 - Remove unecessary line and variable on Line 21 8 | 9 | # Description : Scans directories to check if there are any sqlite files in there 10 | 11 | import os 12 | 13 | def isSQLite3(filename): 14 | from os.path import isfile, getsize 15 | 16 | if not isfile(filename): 17 | return False 18 | if getsize(filename) < 100: # SQLite database file header is 100 bytes 19 | return False 20 | else: 21 | Header = open(filename, 'rb').read(100) 22 | fd.close() 23 | 24 | if Header[0:16] == 'SQLite format 3\000': 25 | return True 26 | else: 27 | return False 28 | 29 | log=open('sqlite_audit.txt','w') 30 | for r,d,f in os.walk(r'.'): 31 | for files in f: 32 | if isSQLite3(files): 33 | print files 34 | print "[+] '%s' **** is a SQLITE database file **** " % os.path.join(r,files) 35 | log.write("[+] '%s' **** is a SQLITE database file **** " % files+'\n') 36 | else: 37 | log.write("[-] '%s' is NOT a sqlite database file" % os.path.join(r,files)+'\n') 38 | log.write("[-] '%s' is NOT a sqlite database file" % files+'\n') 39 | -------------------------------------------------------------------------------- /check_internet_con.py: -------------------------------------------------------------------------------- 1 | import urllib2 2 | 3 | try: 4 | urllib2.urlopen("http://google.com", timeout=2) 5 | print "working connection" 6 | except urllib2.URLError: 7 | print "No internet connection" 8 | -------------------------------------------------------------------------------- /create_dir_if_not_there.py: -------------------------------------------------------------------------------- 1 | # Script Name : create_dir_if_not_there.py 2 | # Author : Craig Richards 3 | # Created : 09th January 2012 4 | # Last Modified : 22nd October 2015 5 | # Version : 1.0.1 6 | # Modifications : Added exceptions 7 | # : 1.0.1 Tidy up comments and syntax 8 | # 9 | # Description : Checks to see if a directory exists in the users home directory, if not then create it 10 | 11 | import os # Import the OS module 12 | try: 13 | home = os.path.expanduser("~") # Set the variable home by expanding the users set home directory 14 | print home # Print the location 15 | 16 | if not os.path.exists(home+'/testdir'): 17 | os.makedirs(home+'/testdir') # If not create the directory, inside their home directory 18 | except Exceptions as e: 19 | print e 20 | -------------------------------------------------------------------------------- /daily_checks.py: -------------------------------------------------------------------------------- 1 | # Script Name : daily_checks.py 2 | # Author : Craig Richards 3 | # Created : 07th December 2011 4 | # Last Modified : 01st May 2013 5 | # Version : 1.5 6 | # 7 | # Modifications : 1.1 Removed the static lines for the putty sessions, it now reads a file, loops through and makes the connections. 8 | # : 1.2 Added a variable filename=sys.argv[0] , as when you use __file__ it errors when creating an exe with py2exe. 9 | # : 1.3 Changed the server_list.txt file name and moved the file to the config directory. 10 | # : 1.4 Changed some settings due to getting a new pc 11 | # : 1.5 Tidy comments and syntax 12 | # 13 | # Description : This simple script loads everything I need to carry out the daily checks for our systems. 14 | 15 | import platform # Load Modules 16 | import os 17 | import subprocess 18 | import sys 19 | 20 | from time import strftime # Load just the strftime Module from Time 21 | 22 | def clear_screen(): # Function to clear the screen 23 | if os.name == "posix": # Unix/Linux/MacOS/BSD/etc 24 | os.system('clear') # Clear the Screen 25 | elif os.name in ("nt", "dos", "ce"): # DOS/Windows 26 | os.system('CLS') # Clear the Screen 27 | 28 | def print_docs(): # Function to print the daily checks automatically 29 | print "Printing Daily Check Sheets:" 30 | # The command below passes the command line string to open word, open the document, print it then close word down 31 | subprocess.Popen(["C:\\Program Files (x86)\Microsoft Office\Office14\winword.exe", "P:\\\\Documentation\\Daily Docs\\Back office Daily Checks.doc", "/mFilePrintDefault", "/mFileExit"]).communicate() 32 | 33 | def putty_sessions(): # Function to load the putty sessions I need 34 | for server in open(conffilename): # Open the file server_list.txt, loop through reading each line - 1.1 -Changed - 1.3 Changed name to use variable conffilename 35 | subprocess.Popen(('putty -load '+server)) # Open the PuTTY sessions - 1.1 36 | 37 | def rdp_sessions(): 38 | print "Loading RDP Sessions:" 39 | subprocess.Popen("mstsc eclr.rdp") # Open up a terminal session connection and load the euroclear session 40 | 41 | def euroclear_docs(): 42 | # The command below opens IE and loads the Euroclear password document 43 | subprocess.Popen('"C:\\Program Files\\Internet Explorer\\iexplore.exe"' '"file://fs1\pub_b\Pub_Admin\Documentation\Settlements_Files\PWD\Eclr.doc"') 44 | 45 | # End of the functions 46 | 47 | # Start of the Main Program 48 | def main(): 49 | filename = sys.argv[0] # Create the variable filename 50 | confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable - 1.3 51 | conffile = ('daily_checks_servers.conf') # Set the variable conffile - 1.3 52 | conffilename = os.path.join(confdir, conffile) # Set the variable conffilename by joining confdir and conffile together - 1.3 53 | clear_screen() # Call the clear screen function 54 | 55 | # The command below prints a little welcome message, as well as the script name, the date and time and where it was run from. 56 | print "Good Morning " + os.getenv('USERNAME') + ", " + filename, "ran at", strftime("%Y-%m-%d %H:%M:%S"), "on",platform.node(), "run from",os.getcwd() 57 | 58 | print_docs() # Call the print_docs function 59 | putty_sessions() # Call the putty_session function 60 | rdp_sessions() # Call the rdp_sessions function 61 | euroclear_docs() # Call the euroclear_docs function 62 | 63 | if __name__ == '__main__': 64 | main() 65 | -------------------------------------------------------------------------------- /dir_test.py: -------------------------------------------------------------------------------- 1 | # Script Name : dir_test.py 2 | # Author : Craig Richards 3 | # Created : 29th November 2011 4 | # Last Modified : 5 | # Version : 1.0 6 | # Modifications : 7 | 8 | # Description : Tests to see if the directory testdir exists, if not it will create the directory for you 9 | 10 | import os # Import the OS module 11 | 12 | if not os.path.exists('testdir'): # Check to see if it exists 13 | os.makedirs('testdir') # Create the directory 14 | -------------------------------------------------------------------------------- /env_check.py: -------------------------------------------------------------------------------- 1 | # Script Name : env_check.py 2 | # Author : Craig Richards 3 | # Created : 14th May 2012 4 | # Last Modified : 14 February 2016 5 | # Version : 1.0.1 6 | 7 | # Modifications : 1.0.1 - Tidy up comments and syntax 8 | 9 | # Description : This script will check to see if all of the environment variables I require are set 10 | 11 | import os 12 | 13 | confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable 14 | conffile = 'env_check.conf' # Set the variable conffile 15 | conffilename = os.path.join(confdir, conffile) # Set the variable conffilename by joining confdir and conffile together 16 | 17 | for env_check in open(conffilename): # Open the config file and read all the settings 18 | env_check = env_check.strip() # Set the variable as itsself, but strip the extra text out 19 | print '[{}]'.format(env_check) # Format the Output to be in Square Brackets 20 | newenv = os.getenv(env_check) # Set the variable newenv to get the settings from the OS what is currently set for the settings out the configfile 21 | 22 | if newenv is None: # If it doesn't exist 23 | print env_check, 'is not set' # Print it is not set 24 | else: # Else if it does exist 25 | print 'Current Setting for {}={}\n'.format(env_check, newenv) # Print out the details 26 | -------------------------------------------------------------------------------- /fileinfo.py: -------------------------------------------------------------------------------- 1 | # Script Name : fileinfo.py 2 | # Author : Not sure where I got this from 3 | # Created : 28th November 2011 4 | # Last Modified : 5 | # Version : 1.0 6 | # Modifications : 7 | 8 | # Description : Show file information for a given file 9 | 10 | 11 | # get file information using os.stat() 12 | # tested with Python24 vegsaeat 25sep2006 13 | import os 14 | import stat # index constants for os.stat() 15 | import time 16 | # pick a file you have ... 17 | file_name = raw_input("Enter a file name: ") 18 | file_stats = os.stat(file_name) 19 | # create a dictionary to hold file info 20 | file_info = { 21 | 'fname': file_name, 22 | 'fsize': file_stats [stat.ST_SIZE], 23 | 'f_lm': time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(file_stats[stat.ST_MTIME])), 24 | 'f_la': time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(file_stats[stat.ST_ATIME])), 25 | 'f_ct': time.strftime("%d/%m/%Y %I:%M:%S %p",time.localtime(file_stats[stat.ST_CTIME])) 26 | } 27 | print 28 | print "file name = %(fname)s" % file_info 29 | print "file size = %(fsize)s bytes" % file_info 30 | print "last modified = %(f_lm)s" % file_info 31 | print "last accessed = %(f_la)s" % file_info 32 | print "creation time = %(f_ct)s" % file_info 33 | print 34 | if stat.S_ISDIR(file_stats[stat.ST_MODE]): 35 | print "This a directory" 36 | else: 37 | print "This is not a directory" 38 | print 39 | print "A closer look at the os.stat(%s) tuple:" % file_name 40 | print file_stats 41 | print 42 | print "The above tuple has the following sequence:" 43 | print """st_mode (protection bits), st_ino (inode number), 44 | st_dev (device), st_nlink (number of hard links), 45 | st_uid (user ID of owner), st_gid (group ID of owner), 46 | st_size (file size, bytes), st_atime (last access time, seconds since epoch), 47 | st_mtime (last modification time), st_ctime (time of creation, Windows)""" 48 | -------------------------------------------------------------------------------- /folder_size.py: -------------------------------------------------------------------------------- 1 | # Script Name : folder_size.py 2 | # Author : Craig Richards 3 | # Created : 19th July 2012 4 | # Last Modified : 22 February 2016 5 | # Version : 1.0.1 6 | 7 | # Modifications : Modified the Printing method and added a few comments 8 | 9 | # Description : This will scan the current directory and all subdirectories and display the size. 10 | 11 | import os # Load the library module 12 | directory = '.' # Set the variable directory to be the current directory 13 | dir_size = 0 # Set the size to 0 14 | 15 | fsizedicr = {'Bytes': 1, 'Kilobytes': float(1)/1024, 'Megabytes': float(1)/(1024*1024), 'Gigabytes': float(1)/(1024*1024 16 | * 17 | 1024)} 18 | 19 | for (path, dirs, files) in os.walk(directory): # Walk through all the directories. For each iteration, os.walk returns the folders, subfolders and files in the dir. 20 | for file in files: # Get all the files 21 | filename = os.path.join(path, file) 22 | dir_size += os.path.getsize(filename) # Add the size of each file in the root dir to get the total size. 23 | 24 | for key in fsizedicr: #iterating through the dictionary 25 | print ("Folder Size: " + str(round(fsizedicr[key]*dir_size, 2)) + " " + key) # round function example: round(4.2384, 2) ==> 4.23 26 | -------------------------------------------------------------------------------- /get_info_remoute_srv.py: -------------------------------------------------------------------------------- 1 | # Script Name : get_info_remoute_srv.py 2 | # Author : Pavel Sirotkin 3 | # Created : 3th April 2016 4 | # Last Modified : - 5 | # Version : 1.0.0 6 | 7 | # Modifications : 8 | 9 | # Description : this will get info about remoute server on linux through ssh connection. Connect these servers must be through keys 10 | 11 | import subprocess 12 | import sys 13 | 14 | 15 | HOSTS = ['proxy1', 'proxy'] 16 | 17 | COMMANDS = ['uname -a', 'uptime'] 18 | 19 | for host in HOSTS: 20 | result = [] 21 | for command in COMMANDS: 22 | ssh = subprocess.Popen(["ssh", "%s" % host, command], 23 | shell=False, 24 | stdout=subprocess.PIPE, 25 | stderr=subprocess.PIPE) 26 | result.append(ssh.stdout.readlines()) 27 | print('--------------- '+host+' --------------- ') 28 | for res in result: 29 | if not res: 30 | print(ssh.stderr.readlines()) 31 | break 32 | else: 33 | print(res) 34 | 35 | 36 | -------------------------------------------------------------------------------- /get_youtube_view.py: -------------------------------------------------------------------------------- 1 | import time 2 | import webbrowser 3 | 4 | #how much views you want 5 | 6 | print("Enjoy your Time\n" +time.ctime()) 7 | for count in range(30): 8 | time.sleep(5) 9 | webbrowser.open("https://www.youtube.com/watch?v=o6A7nf3IeeA") 10 | -------------------------------------------------------------------------------- /logs.py: -------------------------------------------------------------------------------- 1 | # Script Name : logs.py 2 | # Author : Craig Richards 3 | # Created : 13th October 2011 4 | # Last Modified : 14 February 2016 5 | # Version : 1.2 6 | # 7 | # Modifications : 1.1 - Added the variable zip_program so you can set it for the zip program on whichever OS, so to run on a different OS just change the locations of these two variables. 8 | # : 1.2 - Tidy up comments and syntax 9 | # 10 | # Description : This script will search for all *.log files in the given directory, zip them using the program you specify and then date stamp them 11 | 12 | import os # Load the Library Module 13 | from time import strftime # Load just the strftime Module from Time 14 | 15 | logsdir="c:\puttylogs" # Set the Variable logsdir 16 | zip_program="zip.exe" # Set the Variable zip_program - 1.1 17 | 18 | for files in os.listdir(logsdir): # Find all the files in the directory 19 | if files.endswith(".log"): # Check to ensure the files in the directory end in .log 20 | files1=files+"."+strftime("%Y-%m-%d")+".zip" # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension 21 | os.chdir(logsdir) # Change directory to the logsdir 22 | os.system(zip_program + " " + files1 +" "+ files) # Zip the logs into dated zip files for each server. - 1.1 23 | os.remove(files) # Remove the original log files 24 | -------------------------------------------------------------------------------- /merge.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import csv 3 | import pdb 4 | import os 5 | import pandas as pd 6 | 7 | def main(): 8 | directory = [] 9 | for dirs in os.walk("."): 10 | directory.append(dirs) 11 | folders = directory[0][1] 12 | for ff in folders: 13 | if ff != ".git": 14 | allFiles = glob.glob(ff + "/*.csv") 15 | frame = pd.DataFrame() 16 | dfs = [] 17 | for files in allFiles: 18 | df = pd.read_csv(files,index_col=None, header=0) 19 | dfs.append(df) 20 | frame = pd.concat(dfs) 21 | frame.to_csv(ff+"/results.csv") 22 | main() 23 | -------------------------------------------------------------------------------- /move_files_over_x_days.py: -------------------------------------------------------------------------------- 1 | # Script Name : move_files_over_x_days.py # Author : Craig Richards # Created : 8th December 2011 # Last Modified : # Version : 1.0 # Modifications : # Description : This will move all the files from the src directory that are over 240 days old to the destination directory. import shutil, sys, time, os # Import the header files src = 'u:\\test' # Set the source directory dst = 'c:\\test' # Set the destination directory now = time.time() # Get the current time for f in os.listdir(src): # Loop through all the files in the source directory if os.stat(f).st_mtime < now - 240 * 86400: # Work out how old they are, if they are older than 240 days old if os.path.isfile(f): # Check it's a file shutil.move(f, dst) # Move the files -------------------------------------------------------------------------------- /new_script.py: -------------------------------------------------------------------------------- 1 | # Script Name : new_script.py 2 | # Author : Craig Richards 3 | # Created : 20th November 2012 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : 8 | 9 | # Description : This will create a new basic template for a new script 10 | 11 | import os # Load the library module 12 | import sys # Load the library module 13 | import datetime # Load the library module 14 | 15 | text = '''You need to pass an argument for the new script you want to create, followed by the script name. You can use 16 | -python : Python Script 17 | -bash : Bash Script 18 | -ksh : Korn Shell Script 19 | -sql : SQL Script''' 20 | 21 | if len(sys.argv) < 3: 22 | print text 23 | sys.exit() 24 | 25 | if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: 26 | print text 27 | sys.exit() 28 | else: 29 | if '-python' in sys.argv[1]: 30 | config_file="python.cfg" 31 | extension=".py" 32 | elif '-bash' in sys.argv[1]: 33 | config_file="bash.cfg" 34 | extension=".bash" 35 | elif '-ksh' in sys.argv[1]: 36 | config_file="ksh.cfg" 37 | extension=".ksh" 38 | elif '-sql' in sys.argv[1]: 39 | config_file="sql.cfg" 40 | extension=".sql" 41 | else: 42 | print 'Unknown option - ' + text 43 | sys.exit() 44 | 45 | confdir=os.getenv("my_config") 46 | scripts=os.getenv("scripts") 47 | dev_dir="Development" 48 | newfile=sys.argv[2] 49 | output_file=(newfile+extension) 50 | outputdir=os.path.join(scripts,dev_dir) 51 | script=os.path.join(outputdir, output_file) 52 | input_file=os.path.join(confdir,config_file) 53 | old_text=" Script Name : " 54 | new_text=(" Script Name : "+output_file) 55 | if not(os.path.exists(outputdir)): 56 | os.mkdir(outputdir) 57 | newscript = open(script, 'w') 58 | input=open(input_file,'r') 59 | today=datetime.date.today() 60 | old_date= " Created :" 61 | new_date= (" Created : "+today.strftime("%d %B %Y")) 62 | 63 | for line in input: 64 | line = line.replace(old_text, new_text) 65 | line = line.replace(old_date, new_date) 66 | newscript.write(line) 67 | -------------------------------------------------------------------------------- /nmap_scan.py: -------------------------------------------------------------------------------- 1 | # Script Name : nmap_scan.py 2 | # Author : Craig Richards 3 | # Created : 24th May 2013 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : 8 | 9 | # Description : This scans my scripts directory and gives a count of the different types of scripts, you need nmap installed to run this 10 | 11 | import nmap # Import the module 12 | import optparse # Import the module 13 | 14 | def nmapScan(tgtHost, tgtPort): # Create the function, this fucntion does the scanning 15 | nmScan = nmap.PortScanner() 16 | nmScan.scan(tgtHost, tgtPort) 17 | state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state'] 18 | print "[*] " + tgtHost + " tcp/"+tgtPort +" "+state 19 | 20 | def main(): # Main Program 21 | parser = optparse.OptionParser('usage%prog ' + '-H -p ') # Display options/help if required 22 | parser.add_option('-H', dest='tgtHost', type='string', help='specify host') 23 | parser.add_option('-p', dest='tgtPort', type='string', help='port') 24 | (options, args) = parser.parse_args() 25 | tgtHost = options.tgtHost 26 | tgtPorts = str(options.tgtPort).split(',') 27 | 28 | if (tgtHost == None) | (tgtPorts[0] == None): 29 | print parser.usage 30 | exit(0) 31 | 32 | for tgtPort in tgtPorts: # Scan the hosts with the ports etc 33 | nmapScan(tgtHost, tgtPort) 34 | 35 | if __name__ == '__main__': 36 | main() -------------------------------------------------------------------------------- /nslookup_check.py: -------------------------------------------------------------------------------- 1 | # Script Name : nslookup_check.py 2 | # Author : Craig Richards 3 | # Created : 5th January 2012 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : 8 | 9 | # Description : This very simple script opens the file server_list.txt and the does an nslookup for each one to check the DNS entry 10 | 11 | import subprocess # Import the subprocess module 12 | for server in open('server_list.txt'): # Open the file and read each line 13 | subprocess.Popen(('nslookup '+server)) # Run the nslookup command for each server in the list -------------------------------------------------------------------------------- /osinfo.py: -------------------------------------------------------------------------------- 1 | # Script Name : osinfo.py 2 | # Authors : {'geekcomputers': 'Craig Richards', 'dmahugh': 'Doug Mahugh','rutvik1010':'Rutvik Narayana Nadimpally','y12uc231': 'Satyapriya Krishna', 'minto4644':'Mohit Kumar'} 3 | # Created : 5th April 2012 4 | # Last Modified : July 19 2016 5 | # Version : 1.0 6 | 7 | # Modification 1 : Changed the profile to list again. Order is important. Everytime we run script we don't want to see different ordering. 8 | # Modification 2 : Fixed the AttributeError checking for all properties. Using hasttr(). 9 | # Modification 3 : Removed ': ' from properties inside profile. 10 | 11 | 12 | # Description : Displays some information about the OS you are running this script on 13 | 14 | import platform as pl 15 | 16 | profile = [ 17 | 'architecture', 18 | 'linux_distribution', 19 | 'mac_ver', 20 | 'machine', 21 | 'node', 22 | 'platform', 23 | 'processor', 24 | 'python_build', 25 | 'python_compiler', 26 | 'python_version', 27 | 'release', 28 | 'system', 29 | 'uname', 30 | 'version', 31 | ] 32 | 33 | 34 | 35 | for key in profile: 36 | if hasattr(pl,key): 37 | print(key + ": "+ str(getattr(pl,key)())) 38 | 39 | -------------------------------------------------------------------------------- /password_cracker.py: -------------------------------------------------------------------------------- 1 | # Script Name : password_cracker.py 2 | # Author : Craig Richards 3 | # Created : 20 May 2013 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : 8 | 9 | # Description : Old school password cracker using python 10 | 11 | from sys import platform as _platform 12 | 13 | # Check the current operating system to import the correct version of crypt 14 | if _platform == "linux" or _platform == "linux2": 15 | import crypt # Import the module 16 | elif _platform == "darwin": 17 | # Mac OS X 18 | import crypt 19 | elif _platform == "win32": 20 | # Windows 21 | try: 22 | import fcrypt # Try importing the fcrypt module 23 | except ImportError: 24 | print 'Please install fcrypt if you are on Windows' 25 | 26 | 27 | 28 | def testPass(cryptPass): # Start the function 29 | salt = cryptPass[0:2] 30 | dictFile=open('dictionary.txt','r') # Open the dictionary file 31 | for word in dictFile.readlines(): # Scan through the file 32 | word=word.strip('\n') 33 | cryptWord=crypt.crypt(word,salt) # Check for password in the file 34 | if (cryptWord == cryptPass): 35 | print "[+] Found Password: "+word+"\n" 36 | return 37 | print "[-] Password Not Found.\n" 38 | return 39 | 40 | def main(): 41 | passFile = open('passwords.txt') # Open the password file 42 | for line in passFile.readlines(): # Read through the file 43 | if ":" in line: 44 | user=line.split(':')[0] 45 | cryptPass = line.split(':')[1].strip(' ') # Prepare the user name etc 46 | print "[*] Cracking Password For: "+user 47 | testPass(cryptPass) # Call it to crack the users password 48 | 49 | if __name__ == "__main__": 50 | main() 51 | -------------------------------------------------------------------------------- /ping_servers.py: -------------------------------------------------------------------------------- 1 | # Script Name : ping_servers.py 2 | # Author : Craig Richards 3 | # Created : 9th May 2012 4 | # Last Modified : 14th May 2012 5 | # Version : 1.1 6 | 7 | # Modifications : 1.1 - 14th May 2012 - CR Changed it to use the config directory to store the server files 8 | 9 | # Description : This script will, depending on the arguments supplied will ping the servers associated with that application group. 10 | 11 | import os # Load the Library Module 12 | import subprocess # Load the Library Module 13 | import sys # Load the Library Module 14 | 15 | if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called 16 | print ''' 17 | You need to supply the application group for the servers you want to ping, i.e. 18 | dms 19 | swaps 20 | 21 | Followed by the site i.e. 22 | 155 23 | bromley''' 24 | sys.exit(0) 25 | else: 26 | 27 | if (len(sys.argv) < 3): # If no arguments are passed,display the help/instructions on how to run the script 28 | sys.exit ('\nYou need to supply the app group. Usage : ' + filename + ' followed by the application group i.e. \n \t dms or \n \t swaps \n then the site i.e. \n \t 155 or \n \t bromley') 29 | 30 | appgroup = sys.argv[1] # Set the variable appgroup as the first argument you supply 31 | site = sys.argv[2] # Set the variable site as the second argument you supply 32 | 33 | if os.name == "posix": # Check the os, if it's linux then 34 | myping = "ping -c 2 " # This is the ping command 35 | elif os.name in ("nt", "dos", "ce"): # Check the os, if it's windows then 36 | myping = "ping -n 2 " # This is the ping command 37 | 38 | if 'dms' in sys.argv: # If the argument passed is dms then 39 | appgroup = 'dms' # Set the variable appgroup to dms 40 | elif 'swaps' in sys.argv: # Else if the argment passed is swaps then 41 | appgroup = 'swaps' # Set the variable appgroup to swaps 42 | 43 | if '155' in sys.argv: # If the argument passed is 155 then 44 | site = '155' # Set the variable site to 155 45 | elif 'bromley' in sys.argv: # Else if the argument passed is bromley 46 | site = 'bromley' # Set the variable site to bromley 47 | 48 | filename = sys.argv[0] # Sets a variable for the script name 49 | logdir = os.getenv("logs") # Set the variable logdir by getting the OS environment logs 50 | logfile = 'ping_'+appgroup+'_'+site+'.log' # Set the variable logfile, using the arguments passed to create the logfile 51 | logfilename=os.path.join(logdir, logfile) # Set the variable logfilename by joining logdir and logfile together 52 | confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable - 1.2 53 | conffile = (appgroup+'_servers_'+site+'.txt') # Set the variable conffile - 1.2 54 | conffilename=os.path.join(confdir, conffile) # Set the variable conffilename by joining confdir and conffile together - 1.2 55 | 56 | f = open(logfilename, "w") # Open a logfile to write out the output 57 | for server in open(conffilename): # Open the config file and read each line - 1.2 58 | ret = subprocess.call(myping + server, shell=True,stdout=f,stderr=subprocess.STDOUT) # Run the ping command for each server in the list. 59 | if ret == 0: # Depending on the response 60 | f.write (server.strip() + " is alive" + "\n") # Write out that you can receive a reponse 61 | else: 62 | f.write (server.strip() + " did not respond" + "\n") # Write out you can't reach the box 63 | 64 | print ("\n\tYou can see the results in the logfile : "+ logfilename); # Show the location of the logfile -------------------------------------------------------------------------------- /ping_subnet.py: -------------------------------------------------------------------------------- 1 | # Script Name : ping_subnet.py 2 | # Author : Craig Richards 3 | # Created : 12th January 2012 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : 8 | 9 | # Description : After supplying the first 3 octets it will scan the final range for available addresses 10 | 11 | import os # Load the Library Module 12 | import subprocess # Load the Library Module 13 | import sys # Load the Library Module 14 | 15 | filename = sys.argv[0] # Sets a variable for the script name 16 | 17 | if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called 18 | print ''' 19 | You need to supply the first octets of the address Usage : ''' + filename + ''' 111.111.111 ''' 20 | sys.exit(0) 21 | else: 22 | 23 | if (len(sys.argv) < 2): # If no arguments are passed then display the help and instructions on how to run the script 24 | sys.exit (' You need to supply the first octets of the address Usage : ' + filename + ' 111.111.111') 25 | 26 | subnet = sys.argv[1] # Set the variable subnet as the three octets you pass it 27 | 28 | if os.name == "posix": # Check the os, if it's linux then 29 | myping = "ping -c 2 " # This is the ping command 30 | elif os.name in ("nt", "dos", "ce"): # Check the os, if it's windows then 31 | myping = "ping -n 2 " # This is the ping command 32 | 33 | f = open('ping_'+subnet+'.log', 'w') # Open a logfile 34 | for ip in range(2,255): # Set the ip variable for the range of numbers 35 | ret = subprocess.call(myping + str(subnet)+"."+str(ip) , shell=True,stdout=f,stderr=subprocess.STDOUT) # Run the command pinging the servers 36 | if ret == 0: # Depending on the response 37 | f.write (subnet+"."+str(ip) + " is alive" + "\n") # Write out that you can receive a reponse 38 | else: 39 | f.write (subnet+"."+str(ip) + " did not respond" + "\n") # Write out you can't reach the box -------------------------------------------------------------------------------- /portscanner.py: -------------------------------------------------------------------------------- 1 | # Script Name : portscanner.py 2 | # Author : Craig Richards 3 | # Created : 20 May 2013 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : 8 | 9 | # Description : Port Scanner, you just pass the host and the ports 10 | 11 | import optparse # Import the module 12 | from socket import * # Import the module 13 | from threading import * # Import the module 14 | 15 | screenLock = Semaphore(value=1) # Prevent other threads from preceeding 16 | 17 | def connScan(tgtHost, tgtPort): # Start of the function 18 | try: 19 | connSkt = socket(AF_INET, SOCK_STREAM) # Open a socket 20 | connSkt.connect((tgtHost, tgtPort)) 21 | connSkt.send('') 22 | results=connSkt.recv(100) 23 | screenLock.acquire() # Acquire the lock 24 | print '[+] %d/tcp open'% tgtPort 25 | print '[+] ' + str(results) 26 | except: 27 | screenLock.acquire() 28 | print '[-] %d/tcp closed '% tgtPort 29 | finally: 30 | screenLock.release() 31 | connSkt.close() 32 | 33 | def portScan(tgtHost, tgtPorts): # Start of the function 34 | try: 35 | tgtIP = gethostbyname(tgtHost) # Get the IP from the hostname 36 | except: 37 | print "[-] Cannot resolve '%s': Unknown host"%tgtHost 38 | return 39 | try: 40 | tgtName = gethostbyaddr(tgtIP) # Get hostname from IP 41 | print '\n[+] Scan Results for: ' +tgtName[0] 42 | except: 43 | print '\n[+] Scan Results for: ' + tgtIP 44 | setdefaulttimeout(1) 45 | for tgtPort in tgtPorts: # Scan host and ports 46 | t = Thread(target=connScan, args=(tgtHost, int(tgtPort))) 47 | t.start() 48 | 49 | def main(): 50 | parser = optparse.OptionParser('usage %prog -H'+' -p ') 51 | parser.add_option('-H', dest='tgtHost', type='string', help='specify target host') 52 | parser.add_option('-p', dest='tgtPort',type='string', help='specify target port[s] seperated by a comma') 53 | (options, args) = parser.parse_args() 54 | tgtHost = options.tgtHost 55 | tgtPorts = str(options.tgtPort).split(',') 56 | if (tgtHost == None) | (tgtPorts[0] == None): 57 | print parser.usage 58 | exit(0) 59 | portScan(tgtHost, tgtPorts) 60 | if __name__ == '__main__': 61 | main() -------------------------------------------------------------------------------- /powerdown_startup.py: -------------------------------------------------------------------------------- 1 | # Script Name : powerdown_startup.py 2 | # Author : Craig Richards 3 | # Created : 05th January 2012 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : 8 | 9 | # Description : This goes through the server list and pings the machine, if it's up it will load the putty session, if its not it will notify you. 10 | 11 | import os # Load the Library Module 12 | import subprocess # Load the Library Module 13 | from time import strftime # Load just the strftime Module from Time 14 | 15 | def windows(): # This is the function to run if it detects the OS is windows. 16 | f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile 17 | for server in open('startup_list.txt','r'): # Read the list of servers from the list 18 | ret = subprocess.call("ping -n 3 %s" % server, shell=True,stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn 19 | if ret == 0: # If you get a response. 20 | f.write ("%s: is alive, loading PuTTY session" % server.strip() + "\n") # Write out to the logfile 21 | subprocess.Popen(('putty -load '+server)) # Load the putty session 22 | else: 23 | f.write ("%s : did not respond" % server.strip() + "\n") # Write to the logfile if the server is down 24 | 25 | def linux(): 26 | f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile 27 | for server in open('startup_list.txt'): # Read the list of servers from the list 28 | ret = subprocess.call("ping -c 3 %s" % server, shell=True,stdout=open('/dev/null', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn 29 | if ret == 0: # If you get a response. 30 | f.write ("%s: is alive" % server.strip() + "\n") # Print a message 31 | subprocess.Popen(['ssh', server.strip()]) 32 | else: 33 | f.write ("%s: did not respond" % server.strip() + "\n") 34 | 35 | # End of the functions 36 | 37 | # Start of the Main Program 38 | 39 | if os.name == "posix": # If the OS is linux... 40 | linux() # Call the linux function 41 | elif os.name in ("nt", "dos", "ce"): # If the OS is Windows... 42 | windows() # Call the windows function -------------------------------------------------------------------------------- /powerup_checks.py: -------------------------------------------------------------------------------- 1 | # Script Name : powerup_checks.py 2 | # Author : Craig Richards 3 | # Created : 25th June 2013 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : 8 | 9 | # Description : Creates an output file by pulling all the servers for the given site from SQLITE database, then goes through the list pinging the servers to see if they are up on the network 10 | 11 | import sys # Load the Library Module 12 | import sqlite3 # Load the Library Module 13 | import os # Load the Library Module 14 | import subprocess # Load the Library Module 15 | from time import strftime # Load just the strftime Module from Time 16 | 17 | 18 | dropbox=os.getenv("dropbox") # Set the variable, by getting the value of the variable from the OS 19 | config=os.getenv("my_config") # Set the variable, by getting the value of the variable from the OS 20 | dbfile=("Databases/jarvis.db") # Set the variable to the database 21 | master_db=os.path.join(dropbox, dbfile) # Create the variable by linking the path and the file 22 | listfile=("startup_list.txt") # File that will hold the servers 23 | serverfile=os.path.join(config,listfile) # Create the variable by linking the path and the file 24 | outputfile=('server_startup_'+strftime("%Y-%m-%d-%H-%M")+'.log') 25 | 26 | # Below is the help text 27 | 28 | text = ''' 29 | 30 | You need to pass an argument, the options the script expects is 31 | 32 | -site1 For the Servers relating to site1 33 | -site2 For the Servers located in site2''' 34 | 35 | def windows(): # This is the function to run if it detects the OS is windows. 36 | f = open(outputfile, 'a') # Open the logfile 37 | for server in open(serverfile,'r'): # Read the list of servers from the list 38 | #ret = subprocess.call("ping -n 3 %s" % server.strip(), shell=True,stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn 39 | ret = subprocess.call("ping -n 3 %s" % server.strip(),stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn 40 | if ret == 0: # Depending on the response 41 | f.write ("%s: is alive" % server.strip().ljust(15) + "\n") # Write out to the logfile is the server is up 42 | else: 43 | f.write ("%s: did not respond" % server.strip().ljust(15) + "\n") # Write to the logfile if the server is down 44 | 45 | 46 | def linux(): # This is the function to run if it detects the OS is nix. 47 | f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile 48 | for server in open(serverfile,'r'): # Read the list of servers from the list 49 | ret = subprocess.call("ping -c 3 %s" % server, shell=True,stdout=open('/dev/null', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn 50 | if ret == 0: # Depending on the response 51 | f.write ("%s: is alive" % server.strip().ljust(15) + "\n") # Write out to the logfile is the server is up 52 | else: 53 | f.write ("%s: did not respond" % server.strip().ljust(15) + "\n") # Write to the logfile if the server is down 54 | 55 | def get_servers(query): # Function to get the servers from the database 56 | conn = sqlite3.connect(master_db) # Connect to the database 57 | cursor = conn.cursor() # Create the cursor 58 | cursor.execute('select hostname from tp_servers where location =?',(query,)) # SQL Statement 59 | print ('\nDisplaying Servers for : ' + query + '\n') 60 | while True: # While there are results 61 | row = cursor.fetchone() # Return the results 62 | if row == None: 63 | break 64 | f = open(serverfile, 'a') # Open the serverfile 65 | f.write("%s\n" % str(row[0])) # Write the server out to the file 66 | print row[0] # Display the server to the screen 67 | f.close() # Close the file 68 | 69 | def main(): # Main Function 70 | if os.path.exists(serverfile): # Checks to see if there is an existing server file 71 | os.remove(serverfile) # If so remove it 72 | 73 | if len(sys.argv) < 2: # Check there is an argument being passed 74 | print text # Display the help text if there isn't one passed 75 | sys.exit() # Exit the script 76 | 77 | if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # If the ask for help 78 | print text # Display the help text if there isn't one passed 79 | sys.exit(0) # Exit the script after displaying help 80 | else: 81 | if sys.argv[1].lower().startswith('-site1'): # If the argument is site1 82 | query = 'site1' # Set the variable to have the value site 83 | elif sys.argv[1].lower().startswith('-site2'): # Else if the variable is bromley 84 | query = 'site2' # Set the variable to have the value bromley 85 | else: 86 | print '\n[-] Unknown option [-] ' + text # If an unknown option is passed, let the user know 87 | sys.exit(0) 88 | get_servers(query) # Call the get servers funtion, with the value from the argument 89 | 90 | if os.name == "posix": # If the OS is linux. 91 | linux() # Call the linux function 92 | elif os.name in ("nt", "dos", "ce"): # If the OS is Windows... 93 | windows() # Call the windows function 94 | 95 | print ('\n[+] Check the log file ' + outputfile + ' [+]\n') # Display the name of the log 96 | 97 | if __name__ == '__main__': 98 | main() # Call the main function -------------------------------------------------------------------------------- /pscheck.py: -------------------------------------------------------------------------------- 1 | # Script Name : pscheck.py 2 | # Author : Craig Richards 3 | # Created : 19th December 2011 4 | # Last Modified : 17th June 2013 5 | # Version : 1.1 6 | 7 | # Modifications : 1.1 - 17/06/13 - CR - Changed to functions, and check os before running the program 8 | 9 | # Description : Process check on Nix boxes, diplsay formatted output from ps command 10 | 11 | import commands, os, string 12 | 13 | def ps(): 14 | program = raw_input("Enter the name of the program to check: ") 15 | 16 | try: 17 | #perform a ps command and assign results to a list 18 | output = commands.getoutput("ps -f|grep " + program) 19 | proginfo = string.split(output) 20 | 21 | #display results 22 | print "\n\ 23 | Full path:\t\t", proginfo[5], "\n\ 24 | Owner:\t\t\t", proginfo[0], "\n\ 25 | Process ID:\t\t", proginfo[1], "\n\ 26 | Parent process ID:\t", proginfo[2], "\n\ 27 | Time started:\t\t", proginfo[4] 28 | except: 29 | print "There was a problem with the program." 30 | 31 | def main(): 32 | if os.name == "posix": # Unix/Linux/MacOS/BSD/etc 33 | ps() # Call the function 34 | elif os.name in ("nt", "dos", "ce"): # if the OS is windows 35 | print "You need to be on Linux or Unix to run this" 36 | 37 | 38 | if __name__ == '__main__': 39 | main() -------------------------------------------------------------------------------- /puttylogs.py: -------------------------------------------------------------------------------- 1 | # Script Name : puttylogs.py 2 | # Author : Craig Richards 3 | # Created : 13th October 2011 4 | # Last Modified : 29th February 2012 5 | # Version : 1.2 6 | 7 | # Modifications : 1.1 - Added the variable zip_program so you can set it for the zip program on whichever OS, so to run on a different OS just change the locations of these two variables. 8 | # : 1.2 - 29-02-12 - CR - Added shutil module and added one line to move the zipped up logs to the zipped_logs directory 9 | 10 | # Description : Zip up all the logs in the given directory 11 | 12 | import os # Load the Library Module 13 | import shutil # Load the Library Module - 1.2 14 | from time import strftime # Load just the strftime Module from Time 15 | 16 | logsdir="c:\logs\puttylogs" # Set the Variable logsdir 17 | zipdir="c:\logs\puttylogs\zipped_logs" # Set the Variable zipdir - 1.2 18 | zip_program="zip.exe" # Set the Variable zip_program - 1.1 19 | 20 | for files in os.listdir(logsdir): # Find all the files in the directory 21 | if files.endswith(".log"): # Check to ensure the files in the directory end in .log 22 | files1=files+"."+strftime("%Y-%m-%d")+".zip" # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension 23 | os.chdir(logsdir) # Change directory to the logsdir 24 | os.system(zip_program + " " + files1 +" "+ files) # Zip the logs into dated zip files for each server. - 1.1 25 | shutil.move(files1, zipdir) # Move the zipped log files to the zipped_logs directory - 1.2 26 | os.remove(files) # Remove the original log files 27 | -------------------------------------------------------------------------------- /recyclebin.py: -------------------------------------------------------------------------------- 1 | # Script Name : recyclebin.py 2 | # Author : Craig Richards 3 | # Created : 07th June 2013 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : 8 | 9 | # Description : Scans the recyclebin and displays the files in there, originally got this script from the Violent Python book 10 | 11 | import os # Load the Module 12 | import optparse # Load the Module 13 | from _winreg import * # Load the Module 14 | 15 | def sid2user(sid): # Start of the function to gather the user 16 | try: 17 | key = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + '\\' + sid) 18 | (value, type) = QueryValueEx(key, 'ProfileImagePath') 19 | user = value.split('\\')[-1] 20 | return user 21 | except: 22 | return sid 23 | 24 | 25 | def returnDir(): # Start of the function to search through the recyclebin 26 | dirs=['c:\\Recycler\\','C:\\Recycled\\','C:\\$RECYCLE.BIN\\'] 27 | #dirs=['c:\\$RECYCLE.BIN\\'] 28 | for recycleDir in dirs: 29 | if os.path.isdir(recycleDir): 30 | return recycleDir 31 | return None 32 | 33 | def findRecycled(recycleDir): # Start of the function, list the contents of the recyclebin 34 | dirList = os.listdir(recycleDir) 35 | for sid in dirList: 36 | files = os.listdir(recycleDir + sid) 37 | user = sid2user(sid) 38 | print '\n[*] Listing Files for User: ' + str(user) 39 | for file in files: 40 | print '[+] Found File: ' + str(file) 41 | 42 | def main(): 43 | recycleDir = returnDir() 44 | findRecycled(recycleDir) 45 | 46 | if __name__ == '__main__': 47 | main() -------------------------------------------------------------------------------- /script_count.py: -------------------------------------------------------------------------------- 1 | # Script Name : script_count.py 2 | # Author : Craig Richards 3 | # Created : 27th February 2012 4 | # Last Modified : 20th July 2012 5 | # Version : 1.3 6 | 7 | # Modifications : 1.1 - 28-02-2012 - CR - Changed inside github and development functions, so instead of if os.name = "posix" do this else do this etc 8 | # : I used os.path.join, so it condensed 4 lines down to 1 9 | # : 1.2 - 10-05-2012 - CR - Added a line to include PHP scripts. 10 | # : 1.3 - 20-07-2012 - CR - Added the line to include Batch scripts 11 | 12 | # Description : This scans my scripts directory and gives a count of the different types of scripts 13 | 14 | import os # Load the library module 15 | 16 | path = os.getenv("scripts") # Set the variable path by getting the value from the OS environment variable scripts 17 | dropbox = os.getenv("dropbox") # Set the variable dropbox by getting the value from the OS environment variable dropbox 18 | 19 | def clear_screen(): # Function to clear the screen 20 | if os.name == "posix": # Unix/Linux/MacOS/BSD/etc 21 | os.system('clear') # Clear the Screen 22 | elif os.name in ("nt", "dos", "ce"): # DOS/Windows 23 | os.system('CLS') # Clear the Screen 24 | 25 | def count_files(path, extensions): # Start of the function to count the files in the scripts directory, it counts the extension when passed below 26 | counter = 0 # Set the counter to 0 27 | for root, dirs, files in os.walk(path): # Loop through all the directories in the given path 28 | for file in files: # For all the files 29 | counter += file.endswith(extensions) # Count the files 30 | return counter # Return the count 31 | 32 | def github(): # Start of the function just to count the files in the github directory 33 | github_dir = os.path.join(dropbox, 'github') # Joins the paths to get the github directory - 1.1 34 | github_count = sum((len(f) for _, _, f in os.walk(github_dir))) # Get a count for all the files in the directory 35 | if github_count > 5: # If the number of files is greater then 5, then print the following messages 36 | print '\nYou have too many in here, start uploading !!!!!' 37 | print 'You have: ' + str(github_count) + ' waiting to be uploaded to github!!' 38 | elif github_count == 0: # Unless the count is 0, then print the following messages 39 | print '\nGithub directory is all Clear' 40 | else: # If it is any other number then print the following message, showing the number outstanding. 41 | print '\nYou have: ' + str(github_count) + ' waiting to be uploaded to github!!' 42 | 43 | def development(): # Start of the function just to count the files in the development directory 44 | dev_dir = os.path.join(path, 'development') # Joins the paths to get the development directory - 1.1 45 | dev_count = sum((len(f) for _, _, f in os.walk(dev_dir))) # Get a count for all the files in the directory 46 | if dev_count > 10: # If the number of files is greater then 10, then print the following messages 47 | print '\nYou have too many in here, finish them or delete them !!!!!' 48 | print 'You have: ' + str(dev_count) + ' waiting to be finished!!' 49 | elif dev_count ==0: # Unless the count is 0, then print the following messages 50 | print '\nDevelopment directory is all clear' 51 | else: 52 | print '\nYou have: ' + str(dev_count) + ' waiting to be finished!!' # If it is any other number then print the following message, showing the number outstanding. 53 | 54 | clear_screen() # Call the function to clear the screen 55 | 56 | print '\nYou have the following :\n' 57 | print 'AutoIT:\t' + str(count_files(path, '.au3')) # Run the count_files function to count the files with the extension we pass 58 | print 'Batch:\t' + str(count_files(path, ('.bat', ',cmd'))) # 1.3 59 | print 'Perl:\t' + str(count_files(path, '.pl')) 60 | print 'PHP:\t' + str(count_files(path, '.php')) # 1.2 61 | print 'Python:\t' + str(count_files(path, '.py')) 62 | print 'Shell:\t' + str(count_files(path, ('.ksh', '.sh', '.bash'))) 63 | print 'SQL:\t' + str(count_files(path, '.sql')) 64 | 65 | github() # Call the github function 66 | development() # Call the development function 67 | -------------------------------------------------------------------------------- /script_listing.py: -------------------------------------------------------------------------------- 1 | # Script Name : script_listing.py 2 | # Author : Craig Richards 3 | # Created : 15th February 2012 4 | # Last Modified : 29th May 2012 5 | # Version : 1.2 6 | 7 | # Modifications : 1.1 - 28-02-2012 - CR - Added the variable to get the logs directory, I then joined the output so the file goes to the logs directory 8 | # : 1.2 - 29-05/2012 - CR - Changed the line so it doesn't ask for a directory, it now uses the environment varaible scripts 9 | 10 | # Description : This will list all the files in the given directory, it will also go through all the subdirectories as well 11 | 12 | import os # Load the library module 13 | 14 | logdir = os.getenv("logs") # Set the variable logdir by getting the value from the OS environment variable logs 15 | logfile = 'script_list.log' # Set the variable logfile 16 | path = os.getenv("scripts") # Set the varable path by getting the value from the OS environment variable scripts - 1.2 17 | 18 | #path = (raw_input("Enter dir: ")) # Ask the user for the directory to scan 19 | logfilename=os.path.join(logdir, logfile) # Set the variable logfilename by joining logdir and logfile together 20 | log = open(logfilename, 'w') # Set the variable log and open the logfile for writing 21 | for dirpath, dirname, filenames in os.walk(path): # Go through the directories and the subdirectories 22 | for filename in filenames: # Get all the filenames 23 | log.write(os.path.join(dirpath, filename)+'\n') # Write the full path out to the logfile 24 | print "\nYour logfile " , logfilename, "has been created" # Small message informing the user the file has been created -------------------------------------------------------------------------------- /serial_scanner.py: -------------------------------------------------------------------------------- 1 | import serial 2 | import sys 3 | 4 | #A serial port-scanner for linux and windows platforms 5 | 6 | #Author: Julio César Echeverri Marulanda 7 | #e-mail: julio.em7@gmail.com 8 | #blog: blogdelingeniero1.wordpress.com 9 | 10 | #You should have installed the PySerial module to use this method. 11 | 12 | #You can install pyserial with the following line: pip install pyserial 13 | 14 | 15 | def ListAvailablePorts(): 16 | #This function return a list containing the string names for Virtual Serial Ports 17 | #availables in the computer (this function works only for Windows & Linux Platforms but you can extend it) 18 | #if there isn't available ports, returns an empty List 19 | AvailablePorts = [] 20 | platform = sys.platform 21 | if platform == 'win32': 22 | for i in range(255): 23 | try: 24 | ser = serial.Serial(i,9600) 25 | except serial.serialutil.SerialException: 26 | pass 27 | else: 28 | AvailablePorts.append(ser.portstr) 29 | ser.close() 30 | 31 | elif platform == 'linux': 32 | for i in range(0,255): 33 | try: 34 | ser = serial.Serial('/dev/ttyUSB'+str(i)) 35 | except serial.serialutil.SerialException: 36 | pass 37 | else: 38 | AvailablePorts.append('/dev/ttyUSB'+str(i)) 39 | ser.close() 40 | else: 41 | print '''This method was developed only for linux and windows 42 | the current platform isn't recognised''' 43 | return AvailablePorts 44 | 45 | 46 | # EXAMPLE OF HOW IT WORKS 47 | 48 | #if an Arduino is connected to the computer, the port will be show in the terminal 49 | #print ListAvailablePorts() -------------------------------------------------------------------------------- /sqlite_check.py: -------------------------------------------------------------------------------- 1 | # Script Name : sqlite_check.py 2 | # Author : Craig Richards 3 | # Created : 20 May 2013 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : 8 | 9 | # Description : Runs checks to check my SQLITE database 10 | 11 | 12 | import sqlite3 as lite 13 | import sys 14 | import os 15 | 16 | dropbox= os.getenv("dropbox") 17 | dbfile=("Databases\jarvis.db") 18 | master_db=os.path.join(dropbox, dbfile) 19 | con = None 20 | 21 | try: 22 | con = lite.connect(master_db) 23 | cur = con.cursor() 24 | cur.execute('SELECT SQLITE_VERSION()') 25 | data = cur.fetchone() 26 | print "SQLite version: %s" % data 27 | 28 | 29 | except lite.Error, e: 30 | 31 | print "Error %s:" % e.args[0] 32 | sys.exit(1) 33 | 34 | finally: 35 | 36 | if con: 37 | con.close() 38 | 39 | 40 | con = lite.connect(master_db) 41 | cur=con.cursor() 42 | cur.execute("SELECT name FROM sqlite_master WHERE type='table'") 43 | rows = cur.fetchall() 44 | for row in rows: 45 | print row 46 | 47 | con = lite.connect(master_db) 48 | cur=con.cursor() 49 | cur.execute("SELECT name FROM sqlite_master WHERE type='table'") 50 | while True: 51 | row = cur.fetchone() 52 | if row == None: 53 | break 54 | print row[0] -------------------------------------------------------------------------------- /sqlite_table_check.py: -------------------------------------------------------------------------------- 1 | # Script Name : sqlite_table_check.py 2 | # Author : Craig Richards 3 | # Created : 07 June 2013 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : 8 | 9 | # Description : Checks the main SQLITE database to ensure all the tables should exist 10 | 11 | 12 | import sqlite3 13 | import sys 14 | import os 15 | 16 | dropbox= os.getenv("dropbox") 17 | config=os.getenv("my_config") 18 | dbfile=("Databases\jarvis.db") 19 | listfile=("sqlite_master_table.lst") 20 | master_db=os.path.join(dropbox, dbfile) 21 | config_file=os.path.join(config, listfile) 22 | tablelist=open(config_file,'r'); 23 | 24 | conn = sqlite3.connect(master_db) 25 | cursor = conn.cursor() 26 | cursor.execute('SELECT SQLITE_VERSION()') 27 | data = cursor.fetchone() 28 | 29 | if str(data) == "(u'3.6.21',)": 30 | print ("\nCurrently " + master_db + " is on SQLite version: %s" % data + " - OK -\n") 31 | else: 32 | print ("\nDB On different version than master version - !!!!! \n") 33 | conn.close() 34 | 35 | print ("\nCheckling " + master_db + " against " + config_file + "\n") 36 | 37 | for table in tablelist.readlines(): 38 | conn = sqlite3.connect(master_db) 39 | cursor = conn.cursor() 40 | cursor.execute("select count(*) from sqlite_master where name = ?",(table.strip(), )) 41 | res = cursor.fetchone() 42 | 43 | if (res[0]): 44 | print ('[+] Table : ' + table.strip() + ' exists [+]') 45 | else: 46 | print ('[-] Table : ' + table.strip() + ' does not exist [-]') 47 | -------------------------------------------------------------------------------- /testlines.py: -------------------------------------------------------------------------------- 1 | # Script Name : testlines.py 2 | # Author : Craig Richards 3 | # Created : 08th December 2011 4 | # Last Modified : 5 | # Version : 1.0 6 | 7 | # Modifications : beven nyamande 8 | 9 | # Description : This very simple script open a file and prints out 100 lines of whatever is set for the line variableest you want to print\n" # This sets the variable for the text that you want to print 10 | 11 | 12 | def write_to_file(filename,txt): 13 | with open(filename,'w') as file_object: 14 | s = file_object.write(txt) 15 | 16 | 17 | if __name__ == '__main__': 18 | write_to_file('test.txt', 'i am beven') 19 | 20 | -------------------------------------------------------------------------------- /webcam.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | 4 | cap = cv2.VideoCapture(0) 5 | 6 | while(True): 7 | # Capture frame-by-frame 8 | ret, frame = cap.read() 9 | 10 | # Our operations on the frame come here 11 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 12 | 13 | # Display the resulting frame 14 | cv2.imshow('frame',gray) 15 | if cv2.waitKey(1) & 0xFF == ord('q'): 16 | break 17 | 18 | # When everything done, release the capture 19 | cap.release() 20 | cv2.destroyAllWindows() 21 | -------------------------------------------------------------------------------- /work_connect.py: -------------------------------------------------------------------------------- 1 | # Script Name : work_connect.py 2 | # Author : Craig Richards 3 | # Created : 11th May 2012 4 | # Last Modified : 31st October 2012 5 | # Version : 1.1 6 | 7 | # Modifications : 1.1 - CR - Added some extra code, to check an argument is passed to the script first of all, then check it's a valid input 8 | 9 | # Description : This simple script loads everything I need to connect to work etc 10 | 11 | import subprocess # Load the Library Module 12 | import sys # Load the Library Module 13 | import os # Load the Library Module 14 | import time # Load the Library Module 15 | 16 | dropbox = os.getenv("dropbox") # Set the variable dropbox, by getting the values of the environment setting for dropbox 17 | rdpfile = ("remote\\workpc.rdp") # Set the variable logfile, using the arguments passed to create the logfile 18 | conffilename=os.path.join(dropbox, rdpfile) # Set the variable conffilename by joining confdir and conffile together 19 | remote = (r"c:\windows\system32\mstsc.exe ") # Set the variable remote with the path to mstsc 20 | 21 | text = '''You need to pass an argument 22 | -c Followed by login password to connect 23 | -d to disconnect''' # Text to display if there is no argument passed or it's an invalid option - 1.2 24 | 25 | if len(sys.argv) < 2: # Check there is at least one option passed to the script - 1.2 26 | print text # If not print the text above - 1.2 27 | sys.exit() # Exit the program - 1.2 28 | 29 | if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called 30 | print text # Print the text, stored in the text variable - 1.2 31 | sys.exit(0) # Exit the program 32 | else: 33 | if sys.argv[1].lower().startswith('-c'): # If the first argument is -c then 34 | passwd = sys.argv[2] # Set the variable passwd as the second argument passed, in this case my login password 35 | subprocess.Popen((r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe connect -u username -p "+passwd)) 36 | subprocess.Popen((r"c:\geektools\puttycm.exe")) 37 | time.sleep(15) # Sleep for 15 seconds, so the checkpoint software can connect before opening mstsc 38 | subprocess.Popen([remote, conffilename]) 39 | elif sys.argv[1].lower().startswith('-d'): # If the first argument is -d then disconnect my checkpoint session. 40 | subprocess.Popen((r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe disconnect ")) 41 | else: 42 | print 'Unknown option - ' + text # If any other option is passed, then print Unknown option and the text from above - 1.2 --------------------------------------------------------------------------------