[Tutor] Python on Windows with SSH for Cisco devices

2007-07-13 Thread Chris Hallman

Has anyone successfully used Python on Windows with SSH connections to Cisco
devices? I'm referring to using a Python module (Paramiko, pyssh though not
actively developed, Twisted.conch, etc.) and not shelling out via Pexpect
(doesn't work on Windows) or Plink. I need to connect to hundreds of Cisco
routers/switches so that I can run numerous commands to gather data. Here is
a snippet of my Telnet commands that I need working via SSH:

self.tn.write("wr\n")
(index, match, read) = self.tn.expect(["OK"], 15)
if not match:
   self.tn.write("yes\n")
time.sleep(random.uniform(0,2))
self.tn.write("copy tf runn\n")
self.tn.read_until("host []?", 7)
time.sleep(random.uniform(0,2))
self.tn.write("192.168.136.51\n")
self.tn.read_until("filename []?", 7)
time.sleep(random.uniform(0,2))
self.tn.write(self.filename +"\n")
time.sleep(random.uniform(0,2))
self.tn.read_until("[running-config]?", 7)
time.sleep(random.uniform(0,2))
self.tn.write("\n")


I've been able to get the following to work, but the TCP connection closes
after each command:

import paramiko

client = paramiko.SSHClient()

# ignore host keys for the test
client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())

client.connect('host', 22, 'user', 'passw')
(stdin, stdout, stderr) = client.exec_command('sh ver | i IOS')
print stdout.read()


I've read that I can use a dummy channel (not sure the difference between a
channel and a TCP connection) to keep the connection active. I've read the
docs and I've searched the net, but I can't seem to find a good example that
helps. Programming isn't my day job so I'm not that great at it. Any help
would be great.


Thanks!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] script question

2005-09-26 Thread Chris Hallman

I needed a script that takes command line arguments, searches an ini
file for a match to the arguments and then executes a Windows
executable. This is my first script using python so I wanted to make
sure I made
the most of the language. I took bits and pieces from different
tutorials and examples online. The script is executed in this manner:


python search_interface.py device interface interface_name "is down - 00:00:00 01/01/06"



Here is the script:


import ConfigParser, string, sys

section = sys.argv[1]

port = sys.argv[3]

INI=ConfigParser.ConfigParser()

INI.read("interfaces.ini")

passwordentries=[p for p in INI.options(section)]

passwordlist=[INI.get(section, pw) for pw in passwordentries]

print passwordlist

for i in passwordlist:

    if i == port:

      
 os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] +
" " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])



I'd like to know if there is a more efficient way to do this and if
there is a way to have these functions performed with the least amount
of time possible (the ini file could grow quite large).



Thanks!!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] script question

2005-09-28 Thread Chris Hallman

Thanks for all the input!!! I really appreciate it. I need to post a
correction to my script. What I sent was an early version. I made a few
minor modifications:



import ConfigParser, string, sys, ossection = sys.argv[1]interface = sys.argv[3]INI=ConfigParser.ConfigParser()INI.read("c:\utils\interfaces.ini")interface_entries=[p for p in INI.options
(section)]interface_list=[INI.get(section, pw) for pw in interface_entries]for i in interface_list:	if i == interface:		os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet -n l17aesm1 forward red held " + 
sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])



I've researched what you all have suggested and I may need to switch to
reading the ini file line by line or using a different file parser. The
ini file is only 100 lines long now, but will likely grow to 500 line
and maybe to 4000 lines. To give you a better background of what I'm
doing with this script, it's running on a network management system
that receives traps. After some processing of the raw trap, messages
get sent to this script for further processing. These messages are for
interface down traps from routers and switches in our network. I use
this script to mitigate the number of interface down messages on our
console. I need to do this because we do not need to know when every
port has gone down (i.e. user ports). This script searches the ini file
for a device name match. Once it has found a match and if the interface
matches as well, I need to message forwarded to the console (the
Windows command). If no matching device or interface is found, then the
script can just exit.
- Show quoted text -
On 9/26/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Kent Johnson wrote:> *TEST FIRST* Don't optimize until you know it is too slow and you> have a test case that you can time to see if your 'optimizations' are> making it faster.Pardon my shouting :-)
Kent___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] script to change device configuration

2005-10-18 Thread Chris Hallman

I created a script that parses a directory, strips the ".txt"
extension off the file, telnet & log on to the device (the filename
is the device name), opens the associated ".txt" file, sends all the
commands containted in the file to the device and then executes some
commands to save the changes. I'm not very experienced with
programming, writing Python, using functions, OOP, etc., therefore I'd like to
know if there is a better way to do this:

#
# This scripts obtains a directory listing, strips the extensions and telnets to the
# device (which is the filename in the directory). Then it writes the commands in the
# file to the device, saves config and writes it back to SYSMAN. It can be run using:
#    python send_file4.py
#
# Note: "os" is imported for future functionality.
#
# by: TCDH
# on: 10/17/05
# revised: 10/18/05    TCDH - Added logic to check for offline devices and sign-on failures.
#

import telnetlib, re, os, string

dirpath = (r"c:\temp\sun")
dirlist = os.listdir(dirpath)
wpath = (r"c:\temp\py\send_file4.out")
output = file(wpath, "w")
for i in dirlist:
    try:
        tn = telnetlib.Telnet(i.rstrip(".txt"))
        tn.read_until("Username: ")
    except:
        output.write(i.rstrip(".txt") + ": not responding.\n")
        continue
    tn.write("cworks\n")
    (index, match, read) = tn.expect(["Password: "], 5)
    if not match:
        output.write(i.rstrip(".txt") + ": sign-on failure.\n")
        continue
    tn.write("\n")
    tn.write("conf t\n")
    rpath = (dirpath + "\\" + i)
    input = file(rpath, "r")
    for lines in file(rpath):
        tn.write(input.readline())
    tn.write("end\n")    # exit config mode
    tn.write("wr\n")    # save config
    tn.read_until("#")
    tn.write("wr net\n")    #write config to TFTP
    tn.read_until("]? ")
    tn.write("172.16.250.22\n")    # TFTP server address
    tn.read_until("]? ")
    tn.write("\n")
    tn.read_until("[confirm]")
    tn.write("\n")
    tn.read_until("#")
    tn.write("exit\n")    # end session

This script needs to be able to log which device is offline and if
there was a sign-on problem. For the first exception (device offline),
I had to use try-except because tn.expect wouldn't work. However, I had
to use tn.expect on the second exception (sign-on problem) because
try-except wouldn't work there.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] script question

2005-10-18 Thread Chris Hallman
Here is my
latest revision, which works very well.



# This Python script was written to forward interface down messages    

# to ESM1. If the incoming arguements match the interface file

# (c:\utils\interface.ini) then the message is forwarded.

#

# Author:    tcdh

# Date:        09/22/05

# Modified:    10/04/05    changed
os.system to use raw("r") strings. Used % and join method to join

#           
    the sys.argv's. replaced list generating lines with
one line of code.

#                





import ConfigParser, sys, os
section = sys.argv[1]
interface = sys.argv[3]
ini=ConfigParser.ConfigParser()

ini.read("c:\utils\interfaces.ini")

interface_list=ini.items(section)
for i in interface_list:
    if i[1] == interface:

        os.system(r"d:\tnd\bin\delkeep.exe -all -n l17aesm1 %s" % (" ".join(sys.argv[1:3]),)+ "*")

        os.system(r"d:\tnd\bin\cawto.exe
-cat NetNet -n l17aesm1 forward red held %s" % ("
".join(sys.argv[1:5]),))

        break


Again, thank you all for your input. I greatly appreciated it Let me know if you have any further suggestions.

On 9/30/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Chris Hallman wrote:>> Thanks for all the input!!! I really appreciate it. I need to post a> correction to my script. What I sent was an early version. I made a few> minor modifications:
You don't seem to have incorporated any of the suggestions that you have received!I doubt that a 4000-line ini file will be any problem at all.Kent>> import ConfigParser, string, sys, os
> section = sys.argv[1]> interface = sys.argv[3]> INI=ConfigParser.ConfigParser()> INI.read("c:\utils\interfaces.ini")> interface_entries=[p for p in INI.options> (section)]
> interface_list=[INI.get(section, pw) for pw in interface_entries]> for i in interface_list:>   if i == interface:>  
os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet -n l17aesm1 forward red
held " +> sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])>>> I've researched what you all have suggested and I may need to switch to
> reading the ini file line by line or using a different file parser. The> ini file is only 100 lines long now, but will likely grow to 500 line> and maybe to 4000 lines. To give you a better background of what I'm
> doing with this script, it's running on a network management system that> receives traps. After some processing of the raw trap, messages get sent> to this script for further processing. These messages are for interface
> down traps from routers and switches in our network. I use this script> to mitigate the number of interface down messages on our console. I need> to do this because we do not need to know when every port has gone down
> (i.e. user ports). This script searches the ini file for a device name> match. Once it has found a match and if the interface matches as well, I> need to message forwarded to the console (the Windows command). If no
> matching device or interface is found, then the script can just exit.>>> On 9/26/05, *Kent Johnson* <[EMAIL PROTECTED] 
[EMAIL PROTECTED]>> wrote:>> Kent Johnson wrote:>  > *TEST FIRST* Don't optimize until you know it is too slow and you>  > have a test case that you can time to see if your 'optimizations' are
>  > making it faster.>> Pardon my shouting :-)>> Kent>> ___> Tutor maillist  -  
Tutor@python.org Tutor@python.org>> http://mail.python.org/mailman/listinfo/tutor> <
http://mail.python.org/mailman/listinfo/tutor>>>___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] threading issues

2005-10-22 Thread Chris Hallman

I hacked together my first script to learn threading. I'm seeing some weird output. 

This script will PING approximately 1,000 routers. I added a few print
commands for debugging so I can see if it runs faster than a single
threaded script. It blazes through the routers, however I'm seeing
multiple prints (PINGs) for the same device. What is causing this?

Also, I can get fc to write to the file.



#!/usr/bin/env python

#Let us profile code which uses threads
import os, re, string, thread, threading, time
from time import strftime
#from threading import Thread

class PingThread(threading.Thread):
    def run(self):
        pingaf = os.popen('ping -n 1 -w 3 ' + rtr)
        pingas = string.join(pingaf.readlines())
        if ms.search(pingas):
            print
(re.sub('\n','',rtr)) + " responded."    #for debugging
        else:
            pingaf = os.popen('ping -n 2 -w 3 ' + rtr)
            pingas = string.join(pingaf.readlines())
            if ms.search(pingas):
           
    print (re.sub('\n','',rtr)) + "
responded."    # for debugging
            else:
                fc=fc+1
           
    output.write(re.sub('\n','',rtr) + " did not
respond.\n")

fc = 0    # failure counter
ms = re.compile("Reply from")
rpath = (r"c:\temp\py\network_ping_routers.txt")
if os.path.exists(r"c:\temp\py\network_ping_again.txt"):
    rpath = (r"c:\temp\py\network_ping_again.txt")
wpath = (r"c:\temp\py\network_ping.out")
#os.system(r"c:\tnd\bin\cawto.exe -cat NetNet -n l17aesm1 forward blue
held Weekly ISDN testing has started -" + strftime(" %H:%M:%S %x") +
"\n")
output = open(wpath, "a")
output.write("\n" + "\n" + "Network PING test started -" + strftime(" %H:%M:%S %x") + "\n")
output.flush()

for rtr in file(rpath):
    PingThread().start()
print fc    # for debugging
#output.write(fc + " failures found.\n")
output.write("\n" + "\n" + "Network PING test completed -" + strftime(" %H:%M:%S %x") + "\n")
output.close()

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] threading issues

2005-10-23 Thread Chris Hallman

I made a mistake in my first email. I meant that I can't get fc to write to the file. Here is the error:

Traceback (most recent call last):
  File "thread_test_ping.py", line 37, in ?
    output.write(fc + " failures found.\n")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I tried the suggestions you made, but I can't get it to work. Is this what you meant?:

#!/usr/bin/env python

#Let us profile code which uses threads
import os, re, string, thread, threading, time
from time import strftime
#from threading import Thread

class PingThread(threading.Thread):
    def __init__(self, rtr):
        threading.Thread.__init__(self)
        self.rtr = rtr
        PingThread(rtr).start(rtr)
    
    def run(self):
        pingaf = os.popen('ping -n 1 -w 3 ' + rtr)
        pingas = string.join(pingaf.readlines())
        if ms.search(pingas):
            print
(re.sub('\n','',rtr)) + " responded."    #for debugging
        else:
            pingaf = os.popen('ping -n 2 -w 3 ' + rtr)
            pingas = string.join(pingaf.readlines())
            if ms.search(pingas):
           
    print (re.sub('\n','',rtr)) + "
responded."    # for debugging
            else:
                fc=fc+1
           
    output.write(re.sub('\n','',rtr) + " did not
respond.\n")

fc = 0    # failure counter
ms = re.compile("Reply from")
rpath = (r"c:\temp\py\network_ping_routers.txt")
if os.path.exists(r"c:\temp\py\network_ping_again.txt"):
    rpath = (r"c:\temp\py\network_ping_again.txt")
wpath = (r"c:\temp\py\network_ping.out")
#os.system(r"c:\tnd\bin\cawto.exe -cat NetNet -n l17aesm1 forward blue
held Weekly ISDN testing has started -" + strftime(" %H:%M:%S %x") +
"\n")
output = open(wpath, "a")
output.write("\n" + "\n" + "Network PING test started -" + strftime(" %H:%M:%S %x") + "\n")
output.flush()
threads = []
for rtr in file(rpath):
    thread = PingThread()
    thread.start()
    threads.append(thread)
for thread in threads:
    thread.join()
print fc    # for debugging
output.write(fc + " failures found.\n")
output.write("\n" + "\n" + "Network PING test completed -" + strftime(" %H:%M:%S %x") + "\n")
output.close()
On 10/22/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Chris Hallman wrote:>> I hacked together my first script to learn threading. I'm seeing some
> weird output.>> This script will PING approximately 1,000 routers. I added a few print> commands for debugging so I can see if it runs faster than a single> threaded script. It blazes through the routers, however I'm seeing
> multiple prints (PINGs) for the same device. What is causing this?PingThread.run()
uses a global variable - rtr - to determine the router to ping. But
PingThread.run() runs *asynchronously* to the main loop. It's unlikely
that one thread will run for each different value that rtr takes on.
It's possible, for example, that the main loop could complete before
any of the PingThreads gets a chance to run, and each thread would ping
the same router.The solution is to pass the router value to each thread in a constructor:class PingThread(threading.Thread):  def __init__(self, rtr):threading.Thread.__init__(self)self.rtr

 = rtrWhen you create a thread pass it the rtr:  PingThread(rtr).start()then in PingThread.run() you should use self.rtr instead of the global rtr.> Also, I can get fc to write to the file.

Do
you mean you are getting the wrong value of fc written to the file?
This is likely - your main thread will probably complete, and write fc
to output, before all of the pings complete. I would guess that the
main thread completes before *any* of the pings complete, since running
ping takes a second or two.Fixing this is a little harder. You
have to wait for each thread to complete before writing the results.
One way to do this would be to keep track of the threads and join them
all like this:threads = []for rtr in file(rpath):thread = PingThread()thread.start()threads.append(thread)# now wait until all threads are donefor thread in threads:thread.join

()# now you can write fc and it will be correct.Kent>>>> #!/usr/bin/env python>> #Let us profile code which uses threads> import os, re, string, thread, threading, time
> from time import strftime> #from threading import Thread>> class PingThread(threading.Thread):> def run(self):> pingaf = os.popen('ping -n 1 -w 3 ' + rtr)> pingas = 
string.join(pingaf.readlines())> if ms.search(pingas):>
print (re.sub('\n','',rtr)) + " re

Re: [Tutor] threading issues

2005-10-25 Thread Chris Hallman

You're right. I'm inexperienced with classes and threading. The example
you gave (www.wellho.net) was the same example I used as the basis for
my script however I wasn't able to get it to work. I couldn't figure
out what the -q parameter is (it's not a valid parameter on the *nix I
have access to) and when I gave it an IP address range with reachable
and unreachable hosts, it reported them all as alive therefore this
example script isn't a good example. I was able to Google for more
examples.

I was finally able to get my script to not show duplicate PINGs. I also
realized that my script was not PINGing all the hosts in the input
file. Here is my latest version:


import os, re, string, sys, threading, time
from threading import Thread
from time import strftime

ms = re.compile("Reply")
rpath = (r"c:\utils\network_ping_devices.txt")

if os.path.exists(r"c:\utils\network_ping_again.txt"):
    rpath = (r"c:\utils\network_ping_again.txt")
wpath = (r"c:\logs\network_ping.out")
tpath =  (r"c:\temp\ping.txt")
if os.path.exists(tpath):
    os.remove(tpath)
temp = open(tpath, "w")
output = open(wpath, "a")
output.write("\n" + "Network PING test started -" + strftime(" %H:%M:%S %x") + "\n")
output.flush()

class PingIT(threading.Thread):
    def __init__(self,rtr):
        Thread.__init__(self)
        self.rtr = rtr

    def run(self):
        pingaf = os.popen('ping -n 1 -w 3000 ' + self.rtr)
        pingas = string.join(pingaf.readlines())
        if ms.search(pingas):
#            print
(re.sub('\n','',self.rtr)) + " responded."    #for
debugging
            return
        else:
            pingaf = os.popen('ping -n 1 -w 3000 ' + self.rtr)
            pingas = string.join(pingaf.readlines())
            if ms.search(pingas):
#           
    print (re.sub('\n','',self.rtr)) + "
responded."    # for debugging
                return
            else:
           
    temp.write(re.sub('\n','',self.rtr) + " did not
respond.\n")

pinglist = []
for rtr in file(rpath):
    current = PingIT(rtr)
    pinglist.append(current)
    current.start()

for pingle in pinglist:
    pingle.join()

temp.close()
temp = open(tpath, "r")
lines = []
for line in temp:
    lines.append(line.rstrip())
    lines.sort()
for line in lines:
    print >>output, line

output.write("Network PING test completed -" + strftime(" %H:%M:%S %x") + "\n")
output.flush()
output.close()


All the hosts in the input file are sorted alphabetically but my
results were output out of order?! (possibly due to latency in PING
responses or some latency in the thread joining; not sure of either). I
had to do the crude temp output file so that I could sort the results,
but it works!!  
On 10/23/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Chris Hallman wrote:>> I made a mistake in my first email. I meant that I can't get fc to> write to the file. Here is the error:>> Traceback (most recent call last):>   File "thread_test_ping.py", line 37, in ?
> output.write(fc + " failures found.\n")> TypeError: unsupported operand type(s) for +: 'int' and 'str'This
is a pretty easy error to understand. It is saying that you can't add
an int and a string. Looking at your code, you are trying to add fc + "
failures found.\n". fc is indeed an int. You have to change it to a
string to be able to add it to another string. You can do this with the
str() function. So the correct statement is  output.write(str(fc) + " failures found.\n")>> I tried the suggestions you made, but I can't get it to work. Is this> what you meant?:
No, not quite.>> #!/usr/bin/env python>> #Let us profile code which uses threads> import os, re, string, thread, threading, time> from time import strftime> #from threading import Thread
>> class PingThread(threading.Thread):> def __init__(self, rtr):> threading.Thread.__init__(self)> self.rtr = rtrThe
init method initializes a PingThread. It is passed self as an argument,
plus whatever parameters you pass in when you create the PingThread.
You call the superclass constructor and save the value of the
parameter. So far so good...but this next line is creating a
PingThread, it belongs below in your loop.> PingThread(rtr).start(rtr)>> def run(self):Here
you should reference self.rtr so you get the value that was stored in
the call to __init__(), and similarly for each reference to rtr in the
run method.> pingaf = os.popen('ping -n 1 -w 3 ' + rtr)> pingas = string.join(pingaf.readlines())> if ms.search(pingas):>  

[Tutor] TypeError: 'str' object is not callable

2006-02-17 Thread Chris Hallman
Here is my script:send_file.pyimport os, random, re, string, sys, telnetlib, threading, timefrom time import strftimefrom threading import Threadclass ConfigIT(threading.Thread):
    def __init__(self,host):        Thread.__init__(self)        self.host = host        self.filename = filename    def run(self):        try:            tn = telnetlib.Telnet(self.host)
            tn.read_until("Username: ", 7)        except:            output.write(self.host + " - not responding.\n")            output.flush()            return        tn.write(user + "\n")
        tn.read_until("Password: ", 7)        tn.write(pswd + "\n")        (index, match, read) = tn.expect(["#"], 7)        if not match:            output.write(self.host
 + " - sign-on failure.\n")            output.flush()            return        tn.write("conf t\n")        rpath = (dirPath + "\\" + self.filename)        print rpath        input = file(rpath, "r")
        for line in file(rpath):            time.sleep(random.uniform(0,2))            text = input.readline()            tn.write(text)            (index, match, read) = tn.expect(["%"], 1)
            if match:                output.write(self.host + " - config error on line = " + text)                output.flush()                return        tn.write("end\n")        
tn.read_until(self.host.upper() + "#")        time.sleep(random.uniform(0,2))# write config to NVRAM        tn.write("wr\n")        tn.read_until(self.host.upper() + "#")        
time.sleep(random.uniform(0,2))# write config to TFTP        tn.write("wr net\n")        tn.read_until("]?")        time.sleep(random.uniform(0,2))        tn.write("192.168.19.201\n
")        tn.read_until("]?")        time.sleep(random.uniform(0,2))        tn.write("\n")        tn.read_until("[confirm]")        time.sleep(random.uniform(0,2))
        tn.write("\n")        (index, match, read) = tn.expect(["OK"], 15)        if "Error opening tftp" in read:            output.write(self.host + " - config write net failed.\n")
            output.flush()            return# if host = *swa, then write vlan.dat to SYSMAN        m = match_swa.match(self.host)        if m:            tn.write("copy flash tftp\n")
            tn.read_until("]? ")            time.sleep(random.uniform(0,2))            tn.write("vlan.dat\n")            tn.read_until("]? ")            time.sleep(random.uniform
(0,2))            tn.write("192.168.19.201\n")            tn.read_until("dat]? ")            time.sleep(random.uniform(0,2))            tn.write(self.host + ".vlan.dat\n")
            (index, match, read) = tn.expect(["OK"], 15)            if "Error opening tftp" in read:                output.write(self.host + " - VLAN write net failed.\n")                
output.flush()                return        tn.write("exit\n")def count_active():    """ returns the number of Getter threads that are alive """    num_active = 0
    for thread in tlist:        if thread.isAlive():            num_active += 1    return num_activethreads = []dirPath = (r"c:\temp\config")dirList = os.listdir(dirPath)match_swa = 
re.compile('^s\d\d\d\d[s][w][a]')Max_Threads = 10pswd = "Activ8"tlist = []user = "cworks"logFile = (r"c:\logs\send_file.log")output = file(logFile, "a")output.write
("\n" + "send_file script started -" + strftime(" %H:%M:%S %x") + "\n")output.flush()for file in dirList:    filename = file.lower()    host = filename.replace('.txt', '')
    while count_active() >= Max_Threads:        time.sleep(1)    threads = ConfigIT(host)    tlist.append(threads)    threads.start()for thread in tlist:    thread.join()output.write
("send_file script completed -" + strftime(" %H:%M:%S %x") + "\n")output.flush()output.close()Here is the error:
>pythonw -u "send_file.py"c:\temp\config\rtr0544.txtException in thread Thread-1:Traceback (most recent call last):
  File "c:\python24\lib\threading.py", line 442, in __bootstrap    self.run()  File "send_file.py", line 45, in run    input = file(rpath, "r")TypeError: 'str' object is not callable
>Exit code: 0The above script was created using the following script:send_file.r1.py## This script obtains a directory listing, strips the extensions and telnets to the
# device (which is the filename in the directory). Then it writes the commands in the# file to the device, saves config and writes it back to SYSMAN. It can be run using:#    python send_file.py## Note: "os" is imported for future functionality.
## by: TCDH# on: 10/17/05# revised: 10/18/05    TCDH - Added logic to check for offline devices and sign-on failures.#import os, re, string, sys, telnetlib, threading, timefrom time import strftime
from threading import ThreaddirPath = (r"c:\temp\config")dirList = os.listdir(dirPath)pswd = "Activ8"user = "cworks"logFile = (r"c:\logs\send_file.log")
output = file(logFile, "a")output.write("\n" + "send_file script started -" + strftime(" %H:%M:%S %x") + "\n")output.flush()class ConfigIT(threading.Thread
):    def __init__(self,host):        Thread.__init__(self)   

Re: [Tutor] TypeError: 'str' object is not callable

2006-02-17 Thread Chris Hallman
Oh, gee. Do I feel sheepish. I knew I had been staring at the error all along, but yet couldn't see it.Thanks!!On 2/17/06, Kent Johnson
 <[EMAIL PROTECTED]> wrote:Chris Hallman wrote:
>> Here is my script:> input = file(rpath, "r")> for line in file(rpath):> for file in dirList:> filename = file.lower()You use the name 'file' for a global variable. This hides the builtin
function 'file'. This is a bit of a gotcha for newbies - the names ofbuiltins are not reserverd words, so they can be reasigned to your ownvariables. Some of the names that are commonly (mis)used this way are
file, list and dict. You just have to learn not to do this.When you try   input = file(rpath, "r")file contains a string value, which is not callable the way a functionis. Hence the error.
The fix is to use a different name for your variable, e.g. 'f'.Also you are opening the file twice, you don't need the very first lineabove. And 'input' is also the name of a builtin ;)For reference, here is a list of the built-in functions:
http://docs.python.org/lib/built-in-funcs.html> Here is the error:>>  >pythonw -u "send_file.py"> c:\temp\config\rtr0544.txt
> Exception in thread Thread-1:> Traceback (most recent call last):>   File "c:\python24\lib\threading.py", line 442, in __bootstrap> self.run()>   File "send_file.py", line 45, in run
> input = file(rpath, "r")> TypeError: 'str' object is not callableOK, this is saying that you are trying to call a string object, andstrings can't be called. You call something with the () syntax. So the
thing you are trying to call is the value of the symbol 'file'.Evidently that is a string rather than the built-in file function.Kent___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] dictionary manipulation

2006-07-26 Thread Chris Hallman
I need some suggestions on how to work with a dictionary. I've got a program that builds a dictionary. I need to be able to manipulate the different keys and data so that I can write the output to a file AND utilize the smtplib to send the data in an email. I had problems using the data in the dictionary, so I wrote a crude 
for loop to strip characters:
>>> print result{'s0100swa': ['running correct IOS'], 's0300swa': ['INCORRECT running IOS'], 's0200swa': ['running correct IOS'], 's0400swa': ['running correct IOS']}results= sorted(result.items
())>>> print results[('s0100swa', ['running correct IOS']), ('s0200swa', ['running correct IOS']), ('s0300swa', ['INCORRECT running IOS']), ('s0400swa', ['running correct IOS'])]for x in range(len(results)):
    text = repr(results[x])    text = text.replace("'", "")    text = text.replace("(", "")    text = text.replace(")", "")    text = text.replace
("[", "")    text = text.replace("]", "")    text = text.replace(",", ":")    output.write(text + "\n")    output.flush()output.write
("\n")I need to remove the extra characters so the file and email output isn't difficult to read. I also need to be able to use the dictionary data so that I can compose the message used by the smtplib.
Any suggestions?Thanks!!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] help with telnet error

2007-01-17 Thread Chris Hallman

I'm working on a program that telnets to multiple devices to test their
backup ISDN BRI connections. I'm trying to build in error recovery with
try/except logic, but I'm having trouble getting it to work. This first
example uses a host name that isn't in our DNS (yes, this does happen):


import telnetlib
host = "s3793ap01"
telnetlib.Telnet(host)


Traceback (most recent call last):
 File "", line 1, in 
   telnetlib.Telnet(host)
 File "c:\python25\lib\telnetlib.py", line 208, in __init__
   self.open(host, port)
 File "c:\python25\lib\telnetlib.py", line 225, in open
   for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
gaierror: (11001, 'getaddrinfo failed')





try:

   telnetlib.Telnet(host)
except gaierror, e:
   print "error found", e




Traceback (most recent call last):
 File "", line 3, in 
   except gaierror, e:
NameError: name 'gaierror' is not defined




try:

   telnetlib.Telnet(host)
except IOError, e:
   print "error found", e




Traceback (most recent call last):
 File "", line 2, in 
   telnetlib.Telnet(host)
 File "c:\python25\lib\telnetlib.py", line 208, in __init__
   self.open(host, port)
 File "c:\python25\lib\telnetlib.py", line 225, in open
   for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
gaierror: (11001, 'getaddrinfo failed')


As you can see, I'm not sure how to handle the error. Any ideas?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] problem with telnetlib, threading class and try/except

2007-01-17 Thread Chris Hallman

I'm writing a multithreaded program that initiates a dial backup connection
to check the B channels on ISDN BRI connections. I recently added logic to
check for offline devices (Operation timed out) and DNS errors (getaddrinfo
failed). When it encounters the exception, it doesn't appear to be exiting
(by way of the return command) the thread, hence the error.

The input file contains:

rtr3926
s0877ap01

Here is part of the program:
import os, os.path, random, re, socket, string, sys, telnetlib, threading,
time
from time import strftime
from threading import Thread

class ISDNTest(threading.Thread):
   def __init__(self, host):
   Thread.__init__(self)
   self.host = host
   try:
   self.tn = telnetlib.Telnet(self.host)
   except socket.error, err:
   if "Operation timed out" in err:
   print "1st if", self.host, err #progress checking
   dialTestResult[self.host] = ["", "connection timed out"]
   return
   elif "getaddrinfo failed" in err:
   print "2nd if", self.host, err #progress checking
   dialTestResult[self.host] = ["", "DNS resolution failed"]
   return
   self.status = []
   print self.tn #progress checking

   def run(self):
   connect_status = self.Logon()
...(much more program not pasted here)

for entry in inFile:
   if entry == '\n':
   continue
   elif "#" in entry:
   continue
   entry = entry.replace("\n", "")
   while count_active() >= Max_Threads:
   time.sleep(1)
   threads = ISDNTest(entry)
   tlist.append(threads)
   threads.start()

for thread in tlist:
   thread.join()


Here is there error:

pythonw -u "new.isdn.test.py"


log me on rtr3926 (progress checking message, this isn't an error)
1st if s0877ap01 (10060, 'Operation timed out') (progress checking message;
this indicates an exception occurred)
log me on s0877ap01 (progress checking message, this isn't an error)
Exception in thread Thread-2:
Traceback (most recent call last):
 File "c:\python25\lib\threading.py", line 460, in __bootstrap
   self.run()
 File "new.isdn.test.py", line 35, in run
   connect_status = self.Logon()
 File "new.isdn.test.py", line 59, in Logon
   self.tn.read_until("Username:", 7)
AttributeError: 'ISDNTest' object has no attribute 'tn'


Exit code: 0
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] python24dll not found

2007-02-07 Thread Chris Hallman

My apologies if this isn't the correct forum for such a question, however I
was having a problem with Python and couldn't find the cause. I have two
systems running Python. My laptop and a server:

laptop:
WinXP SP2 x86
Python 2.5
pymssql 0.8.0 (for 2.5)
pywin32-210 (for 2.5)

server:
Win2003 no SP dual XEON x86
Python 2.4.1

I develop and test my program on my laptop. I move them to my server and
test again. Then, they go into "production". The few programs I have running
on the server were operating fine until I tried to start running a program
with pymssql. I installed pymssql 0.8.0 (for 2.5) on my laptop so that I
could write and test a new program. When it was ready to move to the server,
I upgraded the server to Python 2.5 and installed pymssql 0.8.0 (for 2.5). I
uninstaled Python 2.4.. The first running of this program gave me a pop-up
error stating that the program failed to start because python24.dll wasn't
found and it recommended reinstalling Python. Python output an error stating
that it couldn't "import _socket". I don't have the exact error because I
was under pressure to restore normal operations. I performed the following:

1. Reinstalled Python 2.5 and execute the program. I received the same
error.
2. Uninstall Python 2.5 and pymssql. Ensure the Python25 directory was
removed. Reinstall Python 2.5 and pymssql. I received the same error.
3. Uninstall Python and pymssql. Ensure the Python25 directory was removed.
Reboot. Reinstall Python 2.5 and pymssql. I received the same error.
4. Uninstall Python 2.5 and pymssql. Ensure the Python25 directory was
removed. Install Python 2.4.2 and pymssql 0.8.0 (for 2.4). The error went
away.


Now all my programs, including the new one, are working again. I have no
clue what caused this. I've searched Google but I can't find a hit similar
to my configuration and situation. Does anyone have an idea as to what could
have caused this?




Chris
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] telnet read_until problems

2007-02-12 Thread Chris Hallman

I've written a program that tests ISDN dial backup at 1,000 locations. I've
broken up the logic into server functions within a threading class (i.e.
logon, get interfaces, get dial string, etc.). At 999 locations, the
following code extract the first of three dial strings:

   def GetDialString(self):
   """ This function extracts the dial string."""
   self.tn.write("term len 0\n")
   self.tn.expect([self.host.upper() + "#"], 7)
   self.tn.write("sh dialer | i Default\n")
   self.data = self.tn.read_until(self.host.upper() + "#", 7)
   print self.data
   match = re.search("\d\d\d\d\d\d\d\d\d\d\d+", self.data)
   if match is not None:
   rc = match.group()
   else:
   rc = "missing"
   return rc

One location doesn't return it's dial string. In Idle, the output is:


print data

sh dialer | i Default
17002111000  1  08w2d   successful   Default
17002111002  0  0never   -   Default
17002111001  1  0never   -   Default
J07MR3640#

The "print data" statement yields:

term len 0
J07MR3640#

I've run a packet capture and I see the data coming back every time. I don't
understand why it works fine for 999 out of 1,000 locations. Any
suggestions?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Telnet and special characters

2007-02-27 Thread Chris Hallman

Is it possible to send a F1 "character" over a telnet connection? I've
searched but I can't find a solution. I've tried
SendKeysand other methods,
but I can't get it to work.

import telnetlib

pswd = "***"
host = "***"
tn = telnetlib.Telnet(host)
tn.read_until("password:", 7)
tn.write(pswd + "\n")
tn.write(chr(27)) # ESC
tn.write(chr(78)) # Shift N
tn.write(chr(25)) # Down arrow
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor