Perl variable value as another variable name - perl

I have a perl script (abc.pl) and 2 config files (one var.pl and one config.txt)
Now
in var.pl
$admin_userid = "admin";
$guest_userid = "guest";
in config.txt - this has the value of user - can be either admin or guest
user=admin/guest
in abc.pl
require var.pl
$get_user = admin or guest (get this value from config.txt)
**$myfinal_userid = ??**
I want the value of myfinal_user_id as admin if user in config.txt is admin and guest if it is guest.
i.e. based on $get_user's value I want the value of userid - ${$get_user}."_userid"
eg: if config.txt has user=admin, the $get_user = admin and I want $myfinal_userid = $admin_userid. similarly for guest. This has to be dynamic.
Finally what I want is, know the user from config.txt and based on it, get the userid from var.pl and store that in myfinal_userid.
Let me know how can I achieve this in perl?

Use a hash to store the id's:
my %id = ( admin => 'admin',
guest => 'guest',
);
my $get_user = 'admin'; # Read this from the config.
my $final_id = $id{$get_user};
my $other_user = 'guest';
my $another_final_id = $id{$other_user};
print $final_id, "\n", $another_final_id, "\n";

Related

Printing a specific value of a Hash?

I want to print (or return at some point), the user input that is located in a hash using ids.
puts "Introduzca su usuario"
user_name = gets.chomp
puts "Ahora su contraseƱa"
user_password = gets.chomp
puts "Un recordatorio de su contraseƱa"
user_reminder = gets.chomp
data = {
user: user_name,
password: user_password,
reminder: user_reminder
}
data.each {|form, value|
puts "Your information is #{value}"
}
Using this I can print every user's input, but what if I want to print just the first, the second or the third?
EDIT
I know I can print directly the user_name, user_password and user_reminder variables, but I want to retrieve a value from the hash itself

A Simple Login/Authorization system using Dancer and Postgres

As a newbie to Perl I'm struggling to find a simple way to do this. I've created a very simple table in my database:
CREATE TABLE users (
id SERIAL NOT NULL PRIMARY KEY,
username TEXT NOT NULL,
password TEXT NOT NULL);
So far I used a simple login system that has a hard coded username and password that I found online:
package Example;
use Dancer ':syntax';
our $VERSION = '0.1';
set session => "Simple";
get '/' => sub {
# template 'index',{},{layout => 0};
template 'index';
};
before sub {
if (! session('user') && request->path_info !~ m{^/login}) {
var requested_path => request->path_info;
request->path_info('/login');
}
};
get '/login' => sub {
# Display a login page; the original URL they requested is available as
# vars->{requested_path}, so could be put in a hidden field in the form
template 'login', { path => vars->{requested_path} }, {layout => 0};
};
post '/login' => sub {
# Validate the username and password they supplied
if (params->{user} eq 'user' && params->{pass} eq 'letmein') {
session user => params->{user};
redirect params->{path} || '/';
} else {
redirect printf 'login failed';
}
};
get '/logout' => sub {
session->destroy;
redirect '/';
};
How do I get started with linking the database and then matching what the user inputs with what's in the database? And also when do I implement the hashing of the passwords? Any tutorials will be greatly appreciated - I've been using metacpan but it's not providing as much detail as I need!
Dancer::Plugin::Auth::Extensible takes care of a lot of boilerplate code for you. You can get a simple login system up and running without having to write any of your own /login routes as follows.
Configure Dancer::Plugin::Auth::Extensible
Install Dancer::Plugin::Database and Dancer::Plugin::Auth::Extensible::Provider::Database and add this to config.yml:
session: "YAML"
plugins:
Auth::Extensible:
realms:
users:
provider: 'Database'
disable_roles: 1
Configure database connection
Configure your database connection in environments/development.yml so that you can have different configurations for dev and production. This is what the configuration looks like for MySQL, with the connection credentials (database name, host, username, and password) stored in a separate options file database.cfg:
plugins:
Database:
dsn: 'dbi:mysql:;mysql_read_default_file=/path/to/database.cfg'
dbi_params:
RaiseError: 1
AutoCommit: 1
For Postgres, you should use a .pgpass file to store your connection credentials. Make sure the file is not world readable. See this Stack Overflow post for an example. Test that your credentials file works on the command line and that your webserver can read it.
Your existing table appears to conform to the suggested schema in the docs, but even if it doesn't, you can adjust the table and column names in the configuration.
Lock down your routes
Add the require_login keyword to a route you want to protect. A /login route will be generated automatically with a basic login form, although you can create your own if you like.
lib/MyApp.pm
package MyApp;
use Dancer ':syntax';
use Dancer::Plugin::Auth::Extensible;
our $VERSION = '0.1';
get '/' => require_login sub {
template 'index';
};
true;
(Yes, that really is all the code you have to write. I told you it takes care of a lot of boilerplate.)
Crypt::SaltedHash is used to hash passwords automatically. Note that you should never store plaintext passwords in your database; when you add a user to your database, you should generate a hash of the password and store the hash.
Note that roles are disabled in this example. If you enable roles, you can do other nifty things like only allow users with the admin role to view admin pages.
The simplest way:
Dancer::Plugin::Authorize::Credentials::PostgreSQL
Here is a good write up how to do it properly: http://perlmaven.com/storing-passwords-in-a-an-easy-but-secure-way
post '/login' => sub {
# Validate the username and password they supplied
if (!params->{user} or !params->{pass}){
redirect printf 'login failed';
}
# use your own encryption
my $auth = auth($login, encrypt($password));
# login successful
if ($auth) {
session user => params->{user};
redirect params->{path} || '/';
} else {
redirect printf 'login failed';
}
};
Regards,
Andras

Fetch all user information with Net::LDAP

Currently have an small perl script what for the given username fetch his email address from the ActiveDirectory using Net::LDAP.
The search part is the following:
my $user = "myuser";
my $mesg = $ldap->search(
base => "dc=some,dc=example,dc=com",
filter => '(&(sAMAccountName=' . $user . ')(mail=*))', #?!?
);
for my $entry ($mesg->entries) {
my $val = $entry->get_value('mail');
say "==$val==";
}
Working ok.
How i should modify the above statement to fetch all available information for the given user myuser? I'm looking to get an perl-ish data structure, such something like next:
my $alldata = search(... all info for the given $user ... );
say Dumper $alldata; #hashref with all stored informations for the $user
It is probably dead simple - but i'm an total AD & LDAP-dumb person...
Edit: When I dump out the $msg->entries (what is an LADP::Entry object) got something, but i'm not sure than it contains everything or only the part of the stored data...
I've done something similar, and I use this to query LDAP:
my $ldapResponse = $ldap->search(base => $base, filter => $filter, attrs => $attrs);
And then this to parse it:
if ($ldapResponse && $ldapResponse->count()) {
$ldapResponse->code && die $ldapResponse->error;
my %domainNames = %{$ldapResponse->as_struct};
foreach my $domainName (keys %domainNames) {
my %ldapResponse;
my %dnHash = %{$domainNames{$domainName}};
foreach my $attr (sort(keys %dnHash)) {
# Note that the value for each key of %dnHash is an array,
# so join it together into a string.
my $value = join(" ", #{$dnHash{$attr}});
$ldapResponse{$attr} = $value;
}
// Dump/use %ldapResponse
}
}
I've never tried to use the ldap->entries in your code, but the above works for me!
I explicitly specify a(long) list of attributes ($attr), but perhaps that's optional as your example shows, and you can get ALL LDAP fields by just skipping that arg to search().

using perl to get users of AD group

I've been trying to get this to print out all the members in "domain users". Problem is, it only prints out a small portion of them, then it just sorta stops. Not sure why. Can someone shed some light on the problem?
#!/usr/bin/perl
use Net::LDAP;
my $uid = "cn=account,cn=users,dc=domain,dc=local";
my $bindPass = "password";
my $ldapServer = "ldap://server.domain.local";
# connect to ldap server
$ldap = Net::LDAP -> new ($ldapServer) || die "Could not connect to server\n";
# bind to ldap server
$ldap -> bind($uid, password => $bindPass);
# search for group
$mesg = $ldap -> search(filter => "(&(cn=Domain Users))", base => "dc=domain,dc=local");
$entry = $mesg -> entry;
# #members = $entry -> get_value ('member;Range=0-*');
#the above entry when uncommented doesn't work either.
#members = $entry -> get_value ('member');
foreach $thing (#members) {
print "$thing\n";
}
From the Net::LDAP docs:
sizelimit => N
A sizelimit that restricts the maximum number of entries to be
returned as a result of the search. A value of 0, and the default,
means that no restriction is requested. Servers may enforce a maximum
number of entries to return.
It might very well be your AD server has a restriction configured. Try checking $mesg->error() after the search.
You might have more success if you use ldap://server.domain.local:3268/ as your URL. AD uses a "mini" ldap server on that port to talk to replicated servers (google "global catalog"); you won't see all attributes on that server, but maybe it's less restrictive as to the maximum number of entries.

Trouble using Telnet in perl?

I'm having some trouble send commands and receiving text/data from the telnet connection that I set up.
#!perl
#Telnet.pl
use Net::Telnet;
# Create a new instance of Net::Telnet,
my $telnetCon = new Net::Telnet (Timeout => 20,
Dump_Log => "dump.log",
Input_Log => "infile.log",
Output_log => "output.log",
Prompt => '/\$ $/') or die "Could not make connection.";
# Connect to the host of the users choice
$telnetCon->open('');
#get username and password from user
my $CXusername = '';
my $CXpassword = '';
my $task = '50104'; # Get this input from the search
# Recreate the login
# Wait for the login: message and then enter the username
$telnetCon->waitfor(match => '/login:/i');
# this method adds a \n to the end of the username, it mimics hitting the enter key after entering your username
$telnetCon->print($CXusername);
$telnetCon->waitfor(match => '/Password:/i');
# does the same as the previous command but for the password
$telnetCon->print($CXpassword);
#Wait for the login successful message
$telnetCon->waitfor(match => '/$/');
$telnetCon->cmd("viewtask 50104");
$telnetCon->cmd(" ");
$telnetCon->cmd(" ");
#output = $telnetCon->cmd("who");
print #output;
($output) = $telnetCon->waitfor(match => '/$/');
print "Output: ",$output;
if($searched =~ /MODIFIED files in Task $_[1] :(.*?)The/s){
# to Logout of the telnet connection
$telnetCon->print("exit");
#return the modified data
return $1;
}
Tell me if the question doesn't make sense, I'll try and reword it.
So this is the telnet view. I get stuck on the first image when i enter the $telnetCon->cmd("viewtask 50140"). I want to get to the second image and continue entering commands into my telnet session.
The Net::Telnet cmd method writes your command (with a \n appended) and waits for the prompt. this is incompatible with your program's waiting for input to complete output.
I think in your case you would want to use a combination of print and getlines and/or waitfor to get this to work