It is no secret that in terms of automating any simple actions, both of them are another powerful script. I read
this little article , and I thought - and why are we worse? I’ll take and describe how to automate simple console actions using python scripts, even though this is a fairly broad topic.
Go!
To make a Python script executable in the console, you need the first line to look like
#!/usr/bin/python
where
/ usr / bin / python is the address of the Python interpreter installed on your system. And, of course, the user who runs the script must have rights to execute it. That is characteristic, it will work only in NIX-systems. In Windows, scripts automatically become executable when establishing a correspondence between the interpreter program and the
.py file type.
In general, Python scripts are a lot like Bash scripts, but in my opinion, they are much more elegant. Consider the basic functions that we may need:
')
listdir(path)
Returns a list of file and folder names in a folder named path.
mkdir(path)
Creates a folder named path.
makedirs(path)
It works similarly to the mkdir () function, but automatically creates all the necessary intermediate folders.
remove(path)
Removes a file named path.
rmdir(path)
Removes a directory named path.
removedirs(path)
It works similarly to the rmdir () function, but automatically deletes all parent empty folders.
rename(src, dst)
Renames a file or folder named src to dst.
open(filename, flag)
Opens a file named filename. Flag is needed to determine the access mode: “r” - read, “w” - write, “a” - append.
read(size)
Reads data from the file with size and returns as a string. If the argument is omitted, then the entire contents of the file are read.
readline()
Reads one line from a file, including the newline character (“\ n”).
readlines()
Reads all lines from a file and returns them as a list.
write(string)
Writes string to file.
writelines(lines)
Writes lines from the lines list to a file. The newline character between them is not added.
tell()
Returns the current position in the file in bytes from the beginning of the file.
seek(offset, whence)
Changes the position to offset. The nature of the positioning depends on the whence argument (default is 0):
1) 0 - new position is counted from the beginning of the file;
2) 1 - from the end of the file;
3) 2 - from the current position in the file;
truncate(size)
Truncates the file to size.
close()
Close the file. Remember! Any opening of a file must be followed by a subsequent closure using this method.
And now - to more special cases.
Mess in my head? Nothing, now we will analyze everything in more detail.
First of all, let's add some interactivity. Otherwise, the meaning in our script, if he will not ask the user anything? :) For keyboard input, the
raw_input () method is used. Why not just
input () ? Because when reading a string through
input (), it is passed through an interpreter that converts the entered string to a command. Hands and itching to enter
rm -rf ... Well, okay, drove on! The syntax for the function is:
login = raw_input("Enter your name: ")
Here
login is a variable in which the string entered by the user is read after pressing
Enter .
Now let's open the file and write some information into it.
gogo = open ("/home/username/helloworld","w")
gogo.write("Hello, world!")
gogo.close()
By the way, I recommend checking, before you perform the above, did you have any necessary file at
/ home / username / helloworld ? Otherwise, everything in him will erase and leave nothing at the crime scene, except for “Hello, world!”.
Well, now let's work directly with the console. Personally, in one code fragment I got the address of the host’s provider from issuing the
host domen.com command. No sooner said than done.
import os
import re
vid = os.popen("host l2tp.corbina.ru")
re_dns = re.compile(r"([\d]+)\.([\d]+)\.([\d]+)\.([\d]+)")
for line in vid.readlines():
hst=re_dns.search(line)
if (hst != None):
break
host=hst.group(0)
print "Corbina host adress is "+host
Wow, how many things ... Well, let's understand. Line by line.
import os
import re
We connect standard libraries of a python that all worked.
os is a library for working with system calls and the console.
re - to work with regular expressions.
vid = os.popen ("host l2tp.corbina.ru")
Here, we kind of “enter into the console” the command
host l2tp.corbina.ru , and push what we get into the
vid variable as a list.
re_dns=re.compile(r"([\d]+)\.([\d]+)\.([\d]+)\.([\d]+)")
This, my friends, is a regular expression conversion.
re_dns is a variable into which a special object is written, obtained using the
re.compile () method. I will not explain the syntax of a regular expression, especially since it is the simplest, I can only say - this is the simplest version of the filter for IP addresses.
for line in vid.readlines():
This is where the for loop starts. I think you have already noticed that in Python, the syntax of the
for loop is quite different from other languages. Here, the
line variable is taken, in which lines from the
vid.readlines () list are written in turn. The lines in the list will end - the cycle will also end. The colon at the end indicates the beginning of the section of statements that occur in the loop. These operators must be separated by tabs or multiple spaces. As soon as we wrote everything that should happen in the loop, we simply write the next statement from the beginning of the line. By the way, this also applies to the conditional
if statement , as can be seen below.
hst=re_dns.search(line)
And here we apply the previously obtained regular expression object to the line
line , as a result of which either the list of matching lines is returned to
hst , or
None if nothing is found.
if (hst != None):
break
Check for the very
None . Pay attention to the indent before
break . As you probably know from other languages, this same
break is a loop termination statement. Thus, as soon as
hst becomes not equal to
None - the cycle is interrupted.
host=hst.group(0)
As I already said, the list of strings matching regular expression is returned to the
hst variable. Actually, more precisely, it is not a list that is returned, but a tuple of elements. And since we interrupted the cycle, as soon as we found the first suitable line, it will be written into the first (also zero) element of the tuple, which we safely reach and write to the
host .
print "Corbina host adress is "+host
And then we display this IP in the console. The
print statement prints the string passed to it into the console, and it also allows string concatenation by simple addition.
Well, actually, that's all for a start. I will ask not to scold too much and not to kick for the raggedness of the narrative, if there are any complaints - I will listen with pleasure and try to correct it.