tenable / pyTenable

Python Library for interfacing into Tenable's platform APIs
https://pytenable.readthedocs.io
MIT License
356 stars 175 forks source link

Getpass with PyTenable #182

Closed zepernick03 closed 4 years ago

zepernick03 commented 4 years ago

When I am entering my password I get a NameError saying that my password is not defined

#Get-Users.py
#This file is used to download Tenable Users from the Tenable.SC Rest API using PyTenable and saved into a local CSV file
from tenable.sc import TenableSC
from datetime import datetime, timedelta, date
import time
import pprint
import getpass

def GetUsers( userFilename, username, password):
    sc = TenableSC('URL')
    sc.login(username, password)

    text_file = open(userFilename, "wt")

    for group in sc.groups.list():
        groupd = sc.groups.details(int(group['id']))
        for user in groupd['users']:
            userd = sc.users.details(int(user['id']))
            #pprint.pprint(userd)
            lastLogin = "Never"
            if userd['lastLogin'] != '0': 
                lastLogin = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(userd['lastLogin'])))
            txtRecord = group['name'] + ","  + user['lastname'] + "," + user['firstname'] + "," + user['username'] + "," + lastLogin + "\n"
            n = text_file.write(txtRecord)

    text_file.close()
    localPath = 'c:/tenable/'
    importPath = localPath
    #users
    userFilename = importPath + "TenableUsers.csv"

#Tenable login info
username = 'username'
p = getpass.getpass(prompt='Password:', stream=None)
GetUsers(userFilename, username, p)
SteveMcGrath commented 4 years ago

I'm gonna need more to work off of than that.

zepernick03 commented 4 years ago

It was a Visual Studio Code Error; never mind thanks

SteveMcGrath commented 4 years ago

I have re-instated your previous comment as there are a few things I wanted to bring up in this thread, however you had edited your original comment instead of adding new comments.

  1. I wanted to caution you around logging in without logging out at the end of the script. In pyTenable 1.0.2 and later, there is support for using a context manager to handle this for you.
  2. Arrow is an awesome library for dealing with time and I think you could benefit from it.
  3. Click is an awesome library and you'd greatly benefit from using it for CLI scripts.
  4. Instead of writing CSV files manually, you should really use the built-in CSV library.
  5. When making list calls, you should take a look at what fields you can pass to get back. In the case of the group.list() call, you don't need to make a details call as just passing the relevant fields gets you what you're looking for.

Tying this all together, you should end up with something that looks more like this:

from tenable.sc import TenableSC
from csv import DictWriter
import arrow, click

@click.command()
@click.option('--filename', '-f', type=click.File('w'), default='user_report.csv', help='CSV Report FIle')
@click.option('--address', '-a', envvar='TSC_ADDRESS', prompt=True, help='Tenable.sc Address')
@click.option('--username', '-u', envvar='TSC_USERNAME', prompt=True, help='Tenable.sc Username')
@click.option('--password', '-p', envvar='TSC_PASSWORD', prompt=True, hide_input=True, help='Tenable.sc Password')
def get_users(filename, address, username, password):
    with TenableSC(address, username=username, password=password) as sc:
        fields = ['Group Name', 'User Lastname', 'User Firstname', 'Username', 'Last Logged In']
        csv = DictWriter(filename, fields, extrasaction='ignore')
        csv.writeheader()
        # refer to field list available here:
        # https://docs.tenable.com/sccv/api/Group.html
        for group in sc.groups.list(fields=['id', 'name', 'users']):
            for u in group['users']:
                user = sc.users.details(u['id'])
                if int(user['lastLogin']) > 0:
                    last_log = arrow.get(int(user['lastLogin'])).strftime('%Y-%m-%d %H:%M:%S')
                else:
                    last_log = 'Never'
                csv.writerow({
                    'Group Name': group.get('name'),
                    'User Lastname': user.get('lastname'),
                    'User Firstname': user.get('firstname'),
                    'Username': user.get('username'),
                    'Last Logged In': last_log,
                })

if __name__ == '__main__':
    get_users()
zepernick03 commented 4 years ago

Thank you for the response I will try this.