Beruflich Dokumente
Kultur Dokumente
Batteries Included
Objective
Standard Modules:
socket
os
urllib
sys
telnetlib
subprocess
paramiko
time
json
logging
requests
re
os module
The OS module provides a portable way of using operating system
dependent functionality. For instance to get a directory list on a
windows machine you can issue :
os.system(ls l)
# will return a unix style list:
drwxr-xr-x 2 Dick Administ 0 Feb 27 22:54 aaaa
-rw-r--r-- 1 Dick Administ 645 Feb 28 22:41 ftp.py
os.system(dir *.*)
# will return windows style list
Volume in drive C has no label.
Volume Serial Number is F017-710B
Directory of C:\cs260\ftp
os.listdir(path) returns a list of the names of the entries in the directory given by path; list
is in arbitrary order and doesnt contain , or .. .
>>> print os.listdir('.')
['aaaa', 'ftp.py']
os.mkdir(path[,mode]) create a directory named path with mode mode. default mode is
0777. Mode is ignored on Windows.
os.rmdir(path) remove (delete) the directory path. This only works if the directory is
empty.
sys module
This module provides a number of functions and variables that
can be used to manipulate different parts of the Python runtime
environment.
The argv list contains the arguments passed to the script, when
the interpreter was started. The first item contains the name of
the script itself.
import sys c:\DevNetCode\Python>python test.py
script name is test.py
print("script name is", sys.argv[0]) there are no arguments!
if len(sys.argv) > 1:
print("there are", len(sys.argv) - 1, c:\DevNetCode\Python>python test.py one two three
"arguments:") script name is test.py
for arg in sys.argv[1:]: there are 3 arguments:
print(arg) one
else: two
print("there are no arguments!") three
sys module
Working with modules
The path list contains a list of directory names where Python looks for
extension modules. When you start Python, this list is initialized from a
mixture of built-in rules, the contents of the PYTHONPATH environment
variable, and the registry contents (on Windows). But since its an ordinary
list, you can also manipulate it from within the program:
import sys
if sys.platform == "win32":
import ntpath
pathmodule = ntpath
elif sys.platform == "mac":
import macpath
pathmodule = macpath
else:
# assume it's a posix platform
import posixpath
pathmodule = posixpath
print(pathmodule)
Typical platform names are win32 for Windows 9X/NT and mac for Macintosh. For
Unix systems, the platform name is usually derived from the output of the uname -
r command, such as irix6, linux2, orsunos5 (Solaris).
sys module
Exiting the program
When you reach the end of the main program, the interpreter is automatically
terminated. If you need to exit in midflight, you can call the sys.exit function
instead. This function takes an optional integer value, which is returned to the
calling program.
import sys
print("hello")
sys.exit(1)
print("there")
subprocess module
The subprocess module allows us to:
spawn new processes
connect to their input/output/error pipes
obtain their return codes
It offers a higher-level interface than some of the other available
modules, and is intended to replace the following functions:
os.system()
os.spawn*()
os.popen*()
popen2.*()
commands.*()
subprocess module
subprocess.call()
We can run the command line with the arguments passed as a list of strings
or by setting the shell argument to a True value. Note, the default value of the
shell argument is False.
>>> import subprocess
>>> subprocess.call('ping 8.8.8.8, shell=True)
print(output)
time module
There is a popular time module available in Python which
provides functions for working with times, and for converting
between representations. The functiontime.time() returns the
current system time in ticks since 12:00am, January 1,
1970(epoch).
import time # This is required to include time module.
ticks = time.time()
print("Number of ticks since 12:00am, January 1, 1970:", ticks)
import time
import subprocess
def main():
while True:
subprocess.call("ping -n 1 8.8.8.8")
time.sleep(5) # delays for 1 seconds
if __name__ == '__main__':
main()
logging module
Logging is a means of tracking events that happen when some
software runs.
Logging provides a set of convenience functions for simple
logging usage. These are debug(), info(), warning(),
error() and critical().
The logging functions are named after the level or severity of
the events they are used to track.
logging module
When to use logging
Task you want to perform The best tool for the task
Display console output for ordinary usage of a command
print()
line script or program
Report events that occur during normal operation of a logging.info() (or logging.debug() for very detailed output
program (e.g. for status monitoring or fault investigation) for diagnostic purposes)
line = ping_out.readlines()
n_received = re.findall(received_packages, str(line))
result = int(n_received[0])
if result == 0:
logging.error("no response")
elif result == 1:
logging.warning("alive, but 50 % packet loss")
elif result == 2:
logging.debug("alive")
else:
logging.critical("unknown issue")
re module
The re module provides regular expression tools for advanced
string processing.
r - Pythons raw string notation for regular expression patterns
s.connect((host, port))
print(s.recv(1024))
s.close() # Close the socket when done
urllib package
urllib.request is a Python module for fetching URLs (Uniform
Resource Locators). It offers a very simple interface, in the form
of the urlopen function. This is capable of fetching URLs using a
variety of different protocols. It also offers a slightly more
complex interface for handling common situations - like basic
authentication, cookies, proxies and so on.
Fetching URLs
import urllib.request
req = urllib.request.Request(http://www.google.com)
response = urllib.request.urlopen(req)
the_page = response.read()
Note that urllib.request makes use of the same Request interface to handle all
URL schemes. For example, you can make an FTP request like so:
req = urllib.request.Request(ftp://ftp.google.com/)
urllib package
You can use a POST to transmit arbitrary data to your own application. In the
common case of HTML forms, the data needs to be encoded in a standard
way, and then passed to the Request object as the data argument. The
encoding is done using a function from the urllib.parse library.
import urllib.parse
import urllib.request
url = "http://www.someserver.com/cgi-bin/register.cgi"
values = {'name': Bill','location' : 'Northampton','language' : 'Python' }
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
the_page = response.read()
urllib package
Headers
When you create a Request object you can pass a dictionary of headers in.
import urllib.parse
import urllib.request
url = http://www.someserver.com/cgi-bin/register.cgi
user_agent = Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)
values = {name : Michael Foord,location : Northampton,language : Python }
req = Request("http://www.google.com")
try:
response = urlopen(req)
except HTTPError as e:
print('The server couldn\'t fulfill the request.')
print('Error code: ', e.code)
except URLError as e:
print('We failed to reach a server.')
print('Reason: ', e.reason)
else:
print("everything is fine")
telnetlib module
The telnetlib module provides a Telnet class that
implements the Telnet protocol.
class telnetlib.Telnet(host=None, port=0[, timeout])
HOST = "192.168.61.1"
user = "admin"
password = "topsecret"
reading_timeout = 5
try:
tn = telnetlib.Telnet(HOST)
tn.read_until(b"Username: ",reading_timeout)
tn.write(user.encode('ascii') + b"\n")
tn.read_until(b"Password: ",reading_timeout)
tn.write(password.encode('ascii') + b"\n")
tn.write(b"terminal length 0\n")
time.sleep(1)
tn.write(b"sh run\n")
tn.write(b"exit\n")
print(tn.read_all().decode('ascii'))
except EOFError:
print("\n\n* Program Exiting...\n")
sys.exit()
finally:
print("Closing connection....")
tn.close()
paramiko module
Paramiko is a Python (2.6+, 3.3+) implementation of the SSHv2
protocol, providing both client and server functionality. While it
leverages a Python C extension for low level cryptography.
Paramiko itself is a pure Python interface around SSH
networking concepts.
import paramiko
ssh = paramiko.SSHClient()
ssh.connect('127.0.0.1', username=admin', password=password')
paramiko module
Host Keys
One of the complicating aspects of SSH authentication is host keys.
The default behavior with an SSHClient object is to refuse to connect to a host
(''paramiko.RejectPolicy'') who does not have a key stored in
your local 'known_hosts' file.
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
stdoutstring = stdout.readlines()
stderrstring = stderr.readlines()
json Module
JSON
The json library can parse JSON from strings or files. The library parses JSON
into a Python dictionary or list. It can also convert Python dictionaries or lists
into JSON strings. >>> import json
.
>>> json dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]
>>> print json .dumps("\"foo\bar")
"\"foo\bar"
>>> print json.dumps(u'\u1234')
"\u1234"
>>> print json.dumps('\\')
"\\
.
>>> print json dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
json Example
Parsing JSON
Take the following string containing JSON data:
json_string = '{"first_name": "Guido", "last_name":"Rossum"}' You can also convert the following to
JSON:
It can be parsed like this:
d = {
import json 'first_name': 'Guido',
parsed_json = json.loads(json_string) 'second_name': 'Rossum',
'titles': ['BDFL', 'Developer'],
and can now be used as a normal dictionary: }
print(json.dumps(d))
print(parsed_json['first_name']) '{"first_name": "Guido", "last_name":
"Guido" "Rossum", "titles": ["BDFL",
"Developer"]}'
requests Module
Requests is the only Non-GMO HTTP library for Python, safe for
human consumption.
Requests allows you to send organic, grass-fed HTTP/1.1 requests, without
the need for manual labor. There's no need to manually add query strings to
your URLs, or to form-encode your POST data. Keep-alive and HTTP
connection pooling are 100% automatic, powered by urllib3, which is
embedded within Requests.
#Now, lets try to get a webpage. For this example, lets get GitHubs public timeline
r = requests.get('https://api.github.com/events')
#Now, we have a Response object called r. We can get all the information we need from this object.
#Requests simple API means that all forms of HTTP request are as obvious. For example, this is how you make
an HTTP POST request:
#Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and OPTIONS? These are all just as
#simple:
#Thats all well and good, but its also only the start of what Requests can do.
Summary