<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>python &#8211; VeriTeknik</title>
	<atom:link href="https://www.veriteknik.net.tr/en/tag/python-2/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.veriteknik.net.tr/en/</link>
	<description>VeriTeknik Bilişim &#124; VeriTeknik Bilişim</description>
	<lastBuildDate>Tue, 22 May 2012 12:12:21 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>System Control Over Python With Pipes</title>
		<link>https://www.veriteknik.net.tr/en/system-control-over-python-with-pipes/</link>
					<comments>https://www.veriteknik.net.tr/en/system-control-over-python-with-pipes/#respond</comments>
		
		<dc:creator><![CDATA[Mustafa Emre Aydın]]></dc:creator>
		<pubDate>Tue, 22 May 2012 12:12:21 +0000</pubDate>
				<category><![CDATA[LINUX]]></category>
		<category><![CDATA[Linux Optimization]]></category>
		<category><![CDATA[Programmin]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[administration]]></category>
		<category><![CDATA[pipe]]></category>
		<category><![CDATA[popen]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">http://www.plugged.in/?p=422</guid>

					<description><![CDATA[<p>Even though major system scripting is usually done via bash (or other shell) scripting, it&#8217;s almost as common to see Python as a system administration scripting platform. Today, most major installers, daemons and package management software are written in Python. While using Python as a system scripting tool, it&#8217;s essential to keep using the standard [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://www.veriteknik.net.tr/en/system-control-over-python-with-pipes/">System Control Over Python With Pipes</a> appeared first on <a rel="nofollow" href="https://www.veriteknik.net.tr/en/">VeriTeknik</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Even though major system scripting is usually done via bash (or other shell) scripting, it&#8217;s almost as common to see Python as a system administration scripting platform. Today, most major installers, daemons and package management software are written in Python.</p>
<p>While using Python as a system scripting tool, it&#8217;s essential to keep using the standard gnu tools if possible, since these tools are reliable, fast and have been tested for years by thousands of other system administrators as well.</p>
<p>The best way to keep using your good old fashioned gnu tools via Python is opening pipes to such tools. Even though it is possible to use the <strong>os</strong> module to do such tasks, the <strong>subprocess</strong> module is more reliable and you have more control over the tasks.</p>
<p>Below you&#8217;ll see two different methods to approach the &#8220;echo&#8221; tool via Python.</p>
<pre class="brush: python; gutter: true; first-line: 1">&gt;&gt;&gt; import os, subprocess
&gt;&gt;&gt; os.system("echo bla")
bla
0
&gt;&gt;&gt; subprocess.Popen(["echo","bla"],stdout=subprocess.PIPE).communicate()[0]
'bla\n'</pre>
<p>As you can see, both give us more or less the same output, but the subprocess module gives us a lot more control. First of all it has pipe support, universal newline support, better handling of exceptions etc.</p>
<p>Below is a method I use to determine the number of processor on the system. Using this, you can find out if you have multiple cores on the system.</p>
<pre class="brush: python; gutter: true; first-line: 1">cpu_num=subprocess.Popen(["grep","-c","processor","/proc/cpuinfo"],stdout=subprocess.PIPE).communicate()[0]</pre>
<p>As you can see, what is does is very very simple, it just counts the number of word &#8220;processor&#8221; in the <strong>/proc/cpuinfo</strong> file using grep.</p>
<p>Don&#8217;t forget that it is very easy to pipe commands through each other with popen, here&#8217;s an example.</p>
<pre class="brush: python; gutter: true; first-line: 1">&gt;&gt;&gt; import subprocess
&gt;&gt;&gt; p1=subprocess.Popen(["cat","/proc/cpuinfo"],stdout=subprocess.PIPE)
&gt;&gt;&gt; p2=subprocess.Popen(["grep","-B","2","-A","2","processor"],stdin=p1.stdout,stdout=subprocess.PIPE)
&gt;&gt;&gt; output = p2.communicate()[0]
&gt;&gt;&gt; print output
processor : 0
vendor_id : GenuineIntel
cpu family : 15</pre>
<p>Using the popen, it is very easy to get information on processes via the pgrep and ps tools. Below is a script when run with the valid parameters, checks if any of it&#8217;s processes uses more (or equal) to the percentage of the CPU specified, if true, kills the process and tries to send a message to the affiliated terminal window.</p>
<p>To accomplish this, we get the pid&#8217;s of the processes via pgrep, send it to ps so to check the cpu percentage and which tty (or pts) it&#8217;s running on. After the check, if necessary, the PID is killed and a message is sent to the terminal it was running on.</p>
<pre class="brush: python; gutter: true; first-line: 1">#!/usr/bin/python
import subprocess, sys, string

if len(sys.argv) != 3 :
    print "Usage : cpukiller.py &lt;process-to-kill&gt; &lt;max-cpu-percentage&gt;"
    raise SystemExit

proc_to_kill = sys.argv[1]
cpu_to_kill = sys.argv[2]

for i in cpu_to_kill :
    if i not in string.digits :
        print "max-cpu-percentage must consist of only digits."
        raise SystemExit

cpu_to_kill = int(cpu_to_kill)

try :
	a=subprocess.Popen(["pgrep",proc_to_kill],stdout=subprocess.PIPE).communicate()[0]
	if a == '' :
		raise SystemExit
	else :
		procc = subprocess.Popen(["ps --no-headers -o pid,pcpu,tname -p $(pgrep %s)"%proc_to_kill],shell=True,stdout=subprocess.PIPE).communicate()[0]
		procc=procc.strip()
except : raise SystemExit 
for lines in procc.split('\n') :
    if lines != '' :
        l=lines.split()
        if int(l[1].split('.')[0]) &gt;= cpu_to_kill :
            if l[2] != '?' :
                try :
                    terminal = open('/dev/'+l[2],'a')
                    subprocess.Popen(["echo","You have exceeded your CPU limit, process with PID %s will be terminated"%l[0]],stdout=terminal).communicate()[0]
                except :
                    print "Couldn't tell the user."
                    pass
            try :
                killer = subprocess.Popen(["kill","-9",l[0]],stdout=subprocess.PIPE).communicate()[0]
            except :
                print "Couldn't kill the process."
                pass
        else : pass</pre>
<p>Try to use it, understand it, and expand it!</p>
<p>The post <a rel="nofollow" href="https://www.veriteknik.net.tr/en/system-control-over-python-with-pipes/">System Control Over Python With Pipes</a> appeared first on <a rel="nofollow" href="https://www.veriteknik.net.tr/en/">VeriTeknik</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.veriteknik.net.tr/en/system-control-over-python-with-pipes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">422</post-id>	</item>
		<item>
		<title>A Simple FTP Status Daemon</title>
		<link>https://www.veriteknik.net.tr/en/a-simple-ftp-status-daemon/</link>
					<comments>https://www.veriteknik.net.tr/en/a-simple-ftp-status-daemon/#respond</comments>
		
		<dc:creator><![CDATA[Mustafa Emre Aydın]]></dc:creator>
		<pubDate>Wed, 25 Apr 2012 07:11:20 +0000</pubDate>
				<category><![CDATA[LINUX]]></category>
		<category><![CDATA[Programmin]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[FTP]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[smtp]]></category>
		<guid isPermaLink="false">http://www.plugged.in/?p=335</guid>

					<description><![CDATA[<p>Here is a clumsy script to check on an FTP Service on a remote server if running or down. The script is written in Python and is a very draft one, but does the job. The main goal is to check whether we get any response from the FTP server while we try to connect [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://www.veriteknik.net.tr/en/a-simple-ftp-status-daemon/">A Simple FTP Status Daemon</a> appeared first on <a rel="nofollow" href="https://www.veriteknik.net.tr/en/">VeriTeknik</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Here is a clumsy script to check on an FTP Service on a remote server if running or down. The script is written in Python and is a very draft one, but does the job.</p>
<p>The main goal is to check whether we get any response from the FTP server while we try to connect anonymously. Don&#8217;t forget that this script probably won&#8217;t work if the FTP server allows anonymous connections.</p>
<p>We simply use the ftplib module to establish the FTP connection. After the successful (or failed) connection, we can report the status of the server via email, to achieve this we use the smtplib module.</p>
<p>The first lines seem simple,</p>
<pre class="brush: python; gutter: true; first-line: 1">#!/usr/bin/python
import ftplib, smtplib
server_ip='10.20.30.40'
sender='sender@email.com'
receivers=['john@email.com','doe@email.com']</pre>
<p>Above, after importing our modules, we&#8217;ve defined the ip address of our FTP server. After that, the sender email address is defined, and then a list containing the receivers.<br />
Now we can define our messages. We&#8217;ll have two messages, one for the UP status, and one for the DOWN.</p>
<pre class="brush: python; gutter: true; first-line: 1">message_up="""
 From: FTP Status DAEMON 
 To: John , Doe 
 Subject: FTP Service Running
The FTP Service on %s is running.
 """ % server_ip
message_down="""
 From: FTP Status DAEMON 
 To: John , Doe 
 Subject: FTP Service DOWN!
The FTP Service on %s is DOWN!!!
 """ % server_ip</pre>
<p>Now we can actually start the checking. The first try clause is checking if we can establish any kind of connection with the server. If the server is somehow down, or if only the FTP service is shut down, this will return some sort of error, which we will catch with the except clause, handle it with our smtp commands, then raise a system exit.</p>
<pre class="brush: python; gutter: true; first-line: 1">try : ftp=ftplib.FTP(server_ip)
except :
 print "FTP DOWN !!!"
 smtpObj = smtplib.SMTP('localhost')
 smtpObj.sendmail(sender,receivers,message_down)
 raise SystemExit</pre>
<p>And here&#8217;s the second check, if we somehow get to this line, it means that we&#8217;ve passed the system exit above, so our connection attempt with the server worked, but we&#8217;re not sure if the FTP service is actually running without a login attempt. When we try to login, and if anonymous connection isn&#8217;t allowed, we&#8217;ll get a permission error, handling it with an exception we can email the recievers that the server is running.</p>
<pre class="brush: python; gutter: true; first-line: 1">try : ftp.login()
except ftplib.error_perm :
 print "FTP Up, Permission Denied."
 smtpObj = smtplib.SMTP('localhost')
 smtpObj.sendmail(sender,receivers,message_up)</pre>
<p>Now simply connect the dots and add the whole script to your crontab, then you&#8217;re good to go!</p>
<p>The post <a rel="nofollow" href="https://www.veriteknik.net.tr/en/a-simple-ftp-status-daemon/">A Simple FTP Status Daemon</a> appeared first on <a rel="nofollow" href="https://www.veriteknik.net.tr/en/">VeriTeknik</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.veriteknik.net.tr/en/a-simple-ftp-status-daemon/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">335</post-id>	</item>
		<item>
		<title>Using the Python API for Yum</title>
		<link>https://www.veriteknik.net.tr/en/using-the-python-api-for-yum/</link>
					<comments>https://www.veriteknik.net.tr/en/using-the-python-api-for-yum/#respond</comments>
		
		<dc:creator><![CDATA[Mustafa Emre Aydın]]></dc:creator>
		<pubDate>Sun, 04 Mar 2012 11:12:32 +0000</pubDate>
				<category><![CDATA[LINUX]]></category>
		<category><![CDATA[Programmin]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[yum]]></category>
		<guid isPermaLink="false">http://www.plugged.in/?p=220</guid>

					<description><![CDATA[<p>Here&#8217;s something very basic yet poorly documented. That&#8217;s why it looks like almost everybody&#8217;s trying to hack their way into this module, the yum module for Python. First of all don&#8217;t forget that this module is only available if you&#8217;re using a Red Hat branch of distribution (fedora, centos etc.) For other distributions, such as [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://www.veriteknik.net.tr/en/using-the-python-api-for-yum/">Using the Python API for Yum</a> appeared first on <a rel="nofollow" href="https://www.veriteknik.net.tr/en/">VeriTeknik</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Here&#8217;s something very basic yet poorly documented. That&#8217;s why it looks like almost everybody&#8217;s trying to hack their way into this module, the yum module for Python.</p>
<p>First of all don&#8217;t forget that this module is only available if you&#8217;re using a Red Hat branch of distribution (fedora, centos etc.) For other distributions, such as Debian, there are other api&#8217;s, such as apt itself.</p>
<p>Below you&#8217;ll find some basic ways of getting configuration settings of the current yum.</p>
<pre class="brush: python; gutter: true; first-line: 1">import yum
yb = yum.YumBase()
print yb.conf.logfile # this will obviously printout the logfile's path
for i in yb.conf.reposdir : print i # and this will printout the directories and files for the repositories
print yb.conf.skip_broken # usually false. when set to true, your yum commands will take action of is the --skip-broken parameters was given to the yum itself.
print yb.conf.errorlevel # this is the level of errors you'd like to get as an output. it's between 0-10 and 0 is only critical ones, while 10 is more like a debug feature. Usually it is set to default 2, but since you'll be running in a script, after your script gets stable, its a good idea to set this to 0 and then distribute it.
print yb.conf.config_file_path # obvious again, the file path for your yum's config file.</pre>
<p>&nbsp;</p>
<p>for more configuration options, you can always see like this;</p>
<pre class="brush: python; gutter: true; first-line: 1">dir(yb.conf)</pre>
<p>and don&#8217;t forget this perfect module, to reverse engineer some function if you don&#8217;t know what arguments it gets and if it&#8217;s poorly documented (ex: it doesn&#8217;t have a valid __doc__ attribute) :</p>
<pre class="brush: python; gutter: true; first-line: 1">import inspect
inspect.getargspec(somefunction)</pre>
<p>And about the arch method. What yum knows about our architecture.</p>
<pre class="brush: python; gutter: true; first-line: 1">import yum
yb = yum.YumBase()
print yb.arch.compatarches # these are the compatible architectures with our system.
# below are the arch types that yum thinks we are usig (hopefully true!)
print yb.arch.canonarch
print yb.arch.basearch
# With the function below, you can get a list of architectures which are compatible with each other.
# Let's say you're using an x86_64 arch, then u can use packages from these ones,
yb.arch.get_arch_list('x86_64')
['x86_64', 'athlon', 'i686', 'i586', 'i486', 'i386', 'noarch']</pre>
<p>If you&#8217;d like to get the currently installed packages on your system, rpm is the module you&#8217;d like to load.</p>
<pre class="brush: python; gutter: true; first-line: 1">import rpm
bold = "\033[1m"
reset = "\033[0;0m"
trans = rpm.TransactionSet()
for header in trans.dbMatch() : print "%s%s%s-%s:%s-%s.%s%s%s" % (bold,header['name'],reset,header['epochnum'],header['version'],header['release'],bold,header['arch'],reset)</pre>
<p>Note that this script outputs various parts in bold. You can use this in any script you&#8217;d like.</p>
<p>Yet here&#8217;s a nice method to install new packages.</p>
<pre class="brush: python; gutter: true; first-line: 1">import yum
yb=yum.YumBase()
searchlist=['name']
arg=['gedit']
matches = yb.searchGenerator(searchlist,arg)
for (package, matched_value) in matches :
    if package.name == 'gedit' : yb.install(package)
    yb.buildTransaction()
    yb.processTransaction()</pre>
<p>&nbsp;</p>
<p>Experiment, enjoy!</p>
<p>The post <a rel="nofollow" href="https://www.veriteknik.net.tr/en/using-the-python-api-for-yum/">Using the Python API for Yum</a> appeared first on <a rel="nofollow" href="https://www.veriteknik.net.tr/en/">VeriTeknik</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.veriteknik.net.tr/en/using-the-python-api-for-yum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">220</post-id>	</item>
	</channel>
</rss>
