Python3 pass variable to paramiko - python-3.x

So i'm taking all ips from the range 1.1.1.0 to 1.1.1.10 and individually connecting to ssh with each ip. When I run "print(host1)" it gives me the ip but when I use the variable host1 in ssh.connect I get the error "getaddrinfo() argument 1 must be string or None" and if I put the variable host1 into quotes I get the error "can only concatenate str (not "IPv4Address") to str"
start_ip = ipaddress.IPv4Address('1.1.1.0')
end_ip = ipaddress.IPv4Address('1.1.1.10')
for ip_int in range(int(start_ip), int(end_ip)):
host1 = ipaddress.IPv4Address(ip_int)
print(ipaddress.IPv4Address(ip_int))
print(host1)
def ssh_connect(password, code=0):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host1, port=22, username=username, password=password, timeout=5)

Python is tab dependent. So you had to be careful about that when you code out your control structures. The indentation tells Python which statements should be included in your loops. My advice is to remove the function definition until you get this piece of code working and then if you wanted to generalize the functionality later when you know Python better, better to have a piece of code that works than a piece of code that you don't quite grasp. But spacing at the beginning of the line is used to indicate the scope of control structures. I never saw that before I started coding with Python and it was the hardest thing for me to grasp. It looks like you might be having trouble with that too.
If you look for the subheading 'Using IP Addresses with other modules' you'll see that you had to typecast the hostname returned by IPv4Address as a string by using str(...)
https://docs.python.org/3/howto/ipaddress.html

Related

How to store result of cmd using Popen with option (input=password) in syntax as mandatory

Part of script in the code, below, is work partial to me, in another words, executed samba-tool command and bring me result on the screen (python3 script.py). BUT, the value of process (variable) is all none.
I tried/read documentations, but without success to store and fix it.
from subprocess import Popen,PIPE, STDOUT
def run_command():
process = Popen(['samba-tool', 'dns','query','chaps.xpto.local','xpto.local','#','ALL','-U','auditor'], stdin=PIPE).communicate(input=b'#!3202#otpX')
print(process)
run_command()
~
I tried:
outs, errs = Popen(['****')
print (outs)
or
print (process.stdout)
I tried to use StringIO to capturing, but sysout of command Popen doesn't record tool
Thank you Ryanwebjackson.
After days suffer with it, I notice that problem is only for syntax samba-tools to query dns information, because the arguments need to inform login/pwd to query and if try capture
output doesn´t works, the utility not understands a valid credetials/bad password.
If i try the syntax to use with other utility or shell commands work well. I decided change the approach and replace :
process = Popen(['samba-tool', 'dns','query','chaps.xpto.local','xpto.local','#','ALL','-U','auditor'], stdin=PIPE).communicate(input=b'#!3202#otpX')
For :
process = subprocess.getoutput("(($(dig +noall +answer "+host+"."+domain+" |wc -c)>0)) && echo exist")
I had the list of host to test if there's records on DNS and zone and voila! fixed.

Allstar Node Programming

I'm almost completely new to Linux programming, and Bash Scripts. I build an amateur radio AllStar node.
I'm trying to create a script that looks at a certain variable and based on that info decides if it should connect or not. I can use a command: asterisk -rx "rpt showvars 47168. This returns a list of variables and their current values. I can store the whole list into a variable that I define, in my test script I just called it MYVAR but I can't seem to only get the value of one of the variables that's listed.
I talked to someone who knows a lot about Linux programming, and she suggested that I try CONNECTED="${MYVAR[3]}" but when I do this, CONNECTED just seems to become a blank variable.
What really frustrates me is I have written programs in other programming languages, and I've been told Bash scripts are easy to learn, but yet I can't seem to get this.
So any help would be great.
how did you assigned your variable?
It seems to me that you want to work with an array, then:
#!/bin/bash
myvar=( $( asterisk -rx "rpt showvars 47168 ) )
echo ${mywar[3]} # this is your fourth element
echo ${#myvar[#]} # this is the total of element in your array
be careful that index in an array starts at 0

IMAP fetch() returns command error: BAD [b' Command Argument Error. 12']

I'm having trouble finding examples/troubleshooting tips online, and am not quite sure that I'm interpreting the documentation correctly. Any assistance would be greatly appreciated.
I'm connecting to an e-mail server, and want to read the e-mail subjects, and bodies. I first make my connection like so:
import imaplib
c = imaplib.IMAP4_SSL(hostname, port)
c.login(username, password)
foldername = 'INBOX/SSR'
c.select(str.encode(foldername), readonly = True)
today = datetime.date.today().strftime('%d-%b-%Y')
searchcriteria = '(SENTON '{}')'.format(today)
typ, msg_ids = c.search(None, searchcriteria)
msg_ids = [s.decode('ascii') for s in msg_ids]
for idnumber in msg_ids:
print(c.fetch(idnumber, "(BODY.PEEK[HEADER])"))
The code and works and output looks as expected, up until the last line, at which point, I get
imaplib.error: FETCH command error: BAD [b' Command Argument Error. 12']
My line of thought, and subsequent testing examined the following possible issues:
bytes vs. string. I converted input back to bytes, but the error remained constant
improper syntax: I tried other commands, such as BODY, SUBJECT, and ENVELOPE but still got the same message.
I'm not sure how to interpret the error, and don't really know where to start. Referencing https://www.rfc-editor.org/rfc/rfc3501.html from pp. 102+, I noticed that the values are labeled differently, but don't understand what the issue is with my implementation. How should I interpret the error? What is wrong with my syntax?
P.S. Correct me if I'm wrong, but the c.search shouldn't change my directory, yes? As in, by selecting foldername, I "navigate" to the selected folder, but just searching only returns values and shouldn't change my location?
I encountered the same problem while I tried to list or select a new mailbox - BAD [b' Command Argument Error. 12'], in my case, it didn't work with “Sent Box”, but it worked well with “Outbox”, so the space symbol is the point.
So it worked with c.select('"{}"'.format("Sent Box")...
Hope this information could help you.
Your last line is not correct msg_ids = [s.decode('ascii') for s in msg_ids]
msg_ids is a list with bytes string, not with elements of a list - example: [b'123 124 125']
Change the last line into msg_ids = msg_ids[0].split(b' ') and it will work as expected.

X3270 Connection and Programming

I'm looking at using a X3270 terminal emulator. I have http://x3270.bgp.nu/ looked over this source material and still don't see how to start using the tool or configure it.
I'm wonder how I can open a terminal and connect. Another question is how could I integrate this into a python program?
edit:
here is a snippet:
em = Emulator()
em.connect(ip)
em.send_string('*user name*')
em.exec_command('Tab')
em.send_string('*user password*')
em.send_enter()
em.send_enter()
em.wait_for_field()
em.save_screen("{0}screenshot".format(*path*))
looking at the save screen i see that the cursor hasn't moved? I can move the cursor using
em.move_to(7,53)
but after that i don't get any text sent through. Any Ideas?
Here's what I do; it works 100% of the time:
from py3270 import *
import sys, os
host = "%s" % sys.argv[1].upper()
try:
e = Emulator()
e.connect(host)
e.wait_for_field()
except WaitError:
print "py3270.connect(%s) failed" % (host)
sys.exit(1)
print "--- connection made to %s ---" % (host)`
If you haven't got a network connection to your host, that wait_for_field() call is going to wait for a full 120 seconds. No matter what I do, I don't seem to be able to affect the length of that timeout.
But your user doesn't have to wait that long, just have him kill your script with a KeyboardInterrupt. Hopefully, your user will grow accustomed to success equaling the display of that "--- connection made ..." message so he'll know he's in trouble when/if the host doesn't respond.
And that's a point I need to make: you don't connect to a terminal (as you described), rather you connect to a host. That host can be either a VTAM connection or some kind of LPAR, usually TSO or z/VM, sometimes CICS or IMS, that VTAM will take you to. Each kind of host has differing prompts & screen content you might need to test for, and sometimes those contents are different depending on whose system you're trying to connect to. Your script becomes the "terminal", depending on what you want to show your user.
What you need to do next depends on what kind of system you're trying to talk to. Through VTAM? (Need to select a VTAM application first?) To z/VM? TSO? Are you logging on or DIALing? What's the next keystroke/field you have to use when you're working with a graphic x3270/c3270 terminal? You need to know that in order to choose your next command.
Good luck!
Please read my comment above first - it would be helpful to have more detail as to what you need to do.
After considering that…have you looked at the py3270 package at https://pypi.python.org/pypi/py3270/0.1.5 ? The summary says it talks to x3270.

Parse data from a shell variable and resuse variable with new data

I have a shell script that I use to do a few things requiring an actual IP address and the DNS name (for readability to the user).
A user will create a shell properties file containing variables that will be used in the script, and one of those variables contains a path and a DNS name for a server. It's setup like this:
PROJ="Blah"
SERVER_NAME="MyServer"
SERVER_PATH="/<path>/$SERVERNAME/aFile/"
In my script, I require the IP address of $SERVER_NAME. So I have a function that extracts the IP address, but I need to substitute that information into the $SERVER_PATH variable and then use the $SERVER_PATH variable. Is there anyway I can do this?
My answer was right in front of me the entire time. I just needed to replace $SERVER_NAME with the IP I obtained from my function.
I essentially just did SERVER_NAME=$SERVER_IP and that was it. I made it much more complicated than it needed to be!

Resources