List windows domain group content from linux - linux

I'd like to list the contents of domain group containing users & computers, then resolve the computer names from dns and prepare list for squid.
What is the best way to do it? I was thinking about connect to ldap using bash or perl, but maybe there is better method.

thanks for help. I created this script, it seems it is working.
#!/bin/bash
oIFS=$IFS
IFS=$'\n'
# list group members
members=( $(ldapsearch -h server -D 'user' -w 'passw' -x -b "DC=domain,DC=net" "(cn=Groupname)" | grep member | awk -F '[=,]' '{print $2}') )
for (( i=0; i<${#members[#]}; i++ ));
do
member=( $(echo "${members[$i]}") )
AccountType=$(ldapsearch -h server -D 'user' -w 'passw' -x -b "DC=domain,DC=net" "(cn=$member)" | grep sAMAccountType | awk '{print $2}')
if [ "$AccountType" == "805306369" ]
then
# this member is PC, let's resolve its IP
host=$(host $member.domain.net)
if [ $? -eq 0 ]; then
ip=$(echo $host| awk '{print $4}')
echo "$member has ip $ip"
else
echo "WARNING: $member not found!"
fi
elif [ "$AccountType" == "805306368" ]
then
echo "$member is User"
else echo "$member is neither PC, nor User"
fi
done
IFS=$oIFS

Related

Bash Scripting checking for home directories

I'm trying to create a script to check if user accounts have valid home directories.
This is what i got at the moment:
#!/bin/bash
cat /etc/passwd | awk -F: '{print $1 " " $3 " " $6 }' | while read user userid directory; do
if [ $userid -ge 1000 ] && [ ! -d "$directory ]; then
echo ${user}
fi
done
This works. I get the expected output which is the username of the account with an invalid home directory.
eg. output
student1
student2
However, I am unable to make it so that ONLY if there is no issues with the valid home directories and all of them are valid, echo "All home directories are valid".
Didn't run it, but it should be something like:
#!/bin/bash
users=()
cat /etc/passwd | awk -F: '{print $1 " " $3 " " $6 }' | while read user userid directory; do
if [ $userid -ge 1000 ] && [ ! -d "$directory" ]; then
users=+("${user}")
fi
done
if test -n ${#users[#]} == 0; then
echo "All home directories are valid"
else
for (( i=0; i<${#users[#]}; i++ )); do echo "${users[$i]}" ; done
fi
You could set a flag, and unset it if you see an invalid directory. Or you could simply check whether your loop printed anything.
You have a number of common antipatterns which you'll want to avoid, too.
# Avoid useless use of cat
# If you are using Awk anyway,
# use it for user id comparison, too
awk -F: '$3 >= 1000 {print $1, $6 }' /etc/passwd |
# Basically always use read -r
while read -r user directory; do
# Fix missing close quote
if [ ! -d "$directory" ]; then
# Quote user
echo "$user"
fi
done |
# If no output, print default message
grep '^' >&2 || echo "No invalid directories" >&2
A proper tool prints its diagnostic output to standard error, not standard output, so I added >&2 to the end.

Looping script, redirect to file

So I have this BASH script and what i want to do is, reach out to the servers. Check the used % of a directory. If it is higher than my set threshold (90) then print that server name to another file on the server where the script has been run from.
What it is doing is printing the first server name twice in to the file so it looks like
server1
server2
Here is my script ... I don't see why it would be going around in a loop to that first server twice
#!/bin/bash
SERVERS="server1
server2"
for i in $SERVERS; do
ssh $SERVERS "
df -h | grep var | awk '{print \$4}' | sed 's/%//g' > /home/user/space.txt
RESULTS=\$(grep -E "1[5-9]" /home/user/space.txt)
THRESHOLD=90
if [[ \$RESULTS -lt \$THRESHOLD ]]; then
exit 1;
elif [[ \$RESULTS -gt \$THRESHOLD ]]; then
hostname;
fi
" >> /home/user/problem.txt
done
Try this,
#!/bin/bash
SERVERS="server1
server2"
for i in $SERVERS; do
ssh "$i" "
df -h | grep var | awk '{print \$4}' | sed 's/%//g' > /home/user/space.txt
RESULTS=\$(grep -E "1[5-9]" /home/user/space.txt)
THRESHOLD=90
if [[ \$RESULTS -lt \$THRESHOLD ]]; then
exit 1;
elif [[ \$RESULTS -gt \$THRESHOLD ]]; then
hostname;
fi
" >> /home/user/problem.txt
done

Masscan & Nmap script

I'm currently studying pen-testing and in the exercise book "Mastering kali linux for advanced penetration testing-second edition" and the script they give for Masscan & Nmap(combined) is this:
#!/bin/bash
function helptext {
echo "enter the massnmap with the file input with list of IP address ranges"
}
if [ "$#" -ne 1 ]; then
echo "Sorry cannot understand the command"
helptext>&2
exit 1
elif [ ! -s $1 ]; then
echo "ooops it is empty"
helptext>&2
exit 1
fi
if [ "$(id -u)" != "0" ]; then
echo "I assunme you are running as root"
helptext>&2
exit 1
fi
for range in $(cat $1); do
store=$(echo $range | sed -e 's/\//_g')
echo "I am trying to create a store to dump now hangon"
mkdir -p pwd/$store;
iptables -A INPUT -p tcp --dport 60000 -j DROP;
echo -e "\n alright lets fire masscan ****"
masscan --open --banners --source-port 60000 -p0-65535 --max-rate 15000 -oBpwd/$store/masscan.bin $range; masscan --read$
if [ ! -s ./results/$store/masscan-output.txt ]; then
echo "Thanks for wasting time"
else
awk'/open/ {print $4, $3, $2, $1}' ./results/$store/masscan-output.txt | awk'
/.+/{
if (! ($1 in Val)) { Key[++i] = $1; }
Val[$1] = Val[$1] $2 ",";
END{
for (j = 1; j <= i; j++) { printf("%s:%s\n%s", Key[j], Val[Key[j]], (j == i) ? "" : "\n"); }
}'>}./results/$store/hostsalive.csv
for ips found in $(cat ./results/$store/hostsalive.csv); do
IP=$(echo $TARGET | awk -F: '{print $1}');
PORT=$(echo $TARGET | awk -F: '{print$2}' | sed's/,$//');
FILENAME=$(echo $IP | awk'{print "nmap_"$1}');
nmap -vv -sV --version-intensity 5 -sT -O --max-rate 5000 -Pn -T3 -p $PORT -oA ./results/$store/$FILENAME $IP;
done
fi
done
I wrote it out by hand just to make sure it was done correctly and when i run after doing chmod +x (filename.sh) it i get:
(running ./filename.sh) i get "Sorry cannot understand the command
enter the massnmap with the file input with list of IP address ranges"
(running ./filename.sh ipran.txt) i get "./anyname.sh: line 37: syntax error near unexpected token found'
./anyname.sh: line 37:for ips found in $(cat ./results/$store/hostsalive.csv); do'"
i am meant to get "I am trying to create a store to dump now hangon" "alright lets fire masscan ****"
i have tried using different ips(in my ipran.txt file)
any help would be greatly appreciated
OS used -Kali linux

Verify account creation from text file in bash script

I am trying to output which accounts have been successfully created from a text file and which haven't. I would also like to output the number of successfully created accounts. I currently the get the following error: grep: 3: No such file or directory. The script and text file and saved in the same folder. I have use the following commands in my script.
file=users.txt
verify =grep "verify" $file |cut -f2 -d:`
cat /etc/passwd | grep $verify
echo -e "\nYou have Currently"
cat /etc/passwd | grep $verify |wc -l;
echo "users added from your Text File"
Edit:
#!/bin/bash
ROOT_UID=0 #The root user has a UID of 0
if [ "$UID" -ne "$ROOT_UID" ]; then
echo "**** You must be the root user to run this script!****"
exit
fi
clear
echo
echo "######################################################"
echo "##### Batch script to automate creation of users #####"
echo -e "######################################################\n"
while true;
do
file=notvalid
while [ $file == "notvalid" ]
do
#echo "repeat $repeat"
#echo -e "\n"
echo -n "Please enter import filename:"
read filename
echo -e "\r"
exists=0
if [ -e $filename ]; then
file=valid
while IFS=":" read firstname lastname userid password group
do
egrep -i "^$userid:" /etc/passwd &>/dev/null
if [ $? -eq 0 ]; then
exists=$((exists+1))
#echo -e "${firstname} ${lastname} already exists on the system"
#grep ${userid} /etc/passwd
aname=$( getent passwd "$userid" | cut -d: -f3)
echo "Account Exists: $aname"
euserid=$( getent passwd "$userid" | cut -d: -f1)
echo "User ID: $userid"
homedir=$( getent passwd "$userid" | cut -d: -f6)
echo "Home Directory: $homedir"
usershell=$( getent passwd "$userid" | cut -d: -f7)
echo "User Shell: $usershell"
g=$( id -Gn "$userid")
echo "Groups: $g"
echo -e "\r"
else
egrep -i "^$group:" /etc/group &>/dev/null
if [ $? -eq 1 ]; then
/usr/sbin/addgroup ${group} &>/dev/null
fi
useradd -d /home/"${userid}" -m -s /bin/bash -c \
"${firstname}${lastname}" -g "${group}" "${userid}"
echo "Creating Account: ${firstname} ${lastname}"
nuserid=$( getent passwd "$userid" | cut -d: -f1)
echo "Creating User ID: ${nuserid}"
{ echo ${password}; echo ${password}; } | sudo passwd ${userid} > /dev/null 2>&1
echo "Creating Password: ${password}"
echo "Creating Home Directory: /home/${userid}"
echo "Creating User Shell: /bin/bash"
echo -e "Assigning Group: ${group}\n"
fi
done < $filename
else
echo -e "##### CANNOT FIND OR LOCATE FILE #####"
fi
verify=`grep "verify" /home/pi/$filename | cut -f3 -d:`
echo "$verify"
count=0
for id in $verify
do grep -wo ^$id /etc/passwd && count=$((count+1))
done
echo $count users added from your text file
echo these are not added:
for id in $verify
do grep -wq ^$id /etc/passwd || echo $id
done
while true
do
echo -n "Create additional accounts [y/n]: "
read opt
if [[ $opt == "n" || $opt == "y" ]];then
break
else
echo "Invalid Input"
fi
done
if [ $opt = "n" ]; then
clear
break
else
clear
fi
done
You were almost there.
The main issue with your approach is that you try to search for multiple accounts at once with grep. The variable verify has multiple userids so you need to process it one by one.
file=users.txt
verify=`grep "verify" $file | cut -f2 -d:`
count=0
for id in $verify
do grep -wo ^$id /etc/passwd && count=$((count+1))
done
echo $count users added from your text file
echo these are not added:
for id in $verify
do grep -wq ^$id /etc/passwd || echo $id
done
The for loop will take each element in your verify variable into id and search with grep (-w matches only whole words, not fragments, ^ matches the beginning of line and -o outputs only the matching word not the whole line).
We count the number of matches in the count variable. Alternative approach to run the for loop twice and pipe the second one to wc -l as you did.
&& operator means it will increase count if the previous command found a match (the return code of grep was 0).
The next loop will not print matching ids (-q), and will echo id if grep did not found a match (the return code was not 0). This is achieved with the || operator.
One last note on iteration of a list: if the members can contain spaces (unlike userids), you should use ${verify[#]} (this is a bash-ism) instead of $verify .
And forget this: cat /etc/passwd | grep pattern, use grep pattern /etc/passwd instead.

Checking if domain is active on server

I am trying to check if a domain is active on the server. So far I get errors.
list=/root/domainlist.txt
for i in $(cat $list)
do
echo "checking " $i
$ip = host $i |grep -o -m 100 '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'
if [[ $ip == "xx.xx.xx.xx" ]]; then
$i >> /root/activedomains.txt
fi
done
Output:
activedomains: line 4: =: command not found
This is the current error I get.
No spaces before and after the =
No dollar sign in the assignment
You probably want the result of the command, so enclose it in $( )
ip=$(host $i |grep -o -m 100 '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}')
write to the file like this
echo "$i" >> /root/activedomains.txt
You have a syntax error with the line
$ip = host $i |grep -o -m 100 '...'
you shoud use instead :
ip=$(host $i |grep -o -m 100 '...')
A better way using boolean logic (no need grep there, if host $ip failed, it will return FALSE):
list=/root/domainlist.txt
while read ip; do
echo "checking $ip"
host "$ip" &>/dev/null && echo "$ip" >> /root/activedomains.txt
done < "$list"
It's the equivalent of
list=/root/domainlist.txt
while read ip; do
echo "checking $ip"
if host "$ip" &>/dev/null; then
echo "$ip" >> /root/activedomains.txt
fi
done < "$list"
For starters you shouldn't assign to $ip to ip ... but it's possible there are more errors.
My guess would be you wanted (line 4/5):
ip=$(host $i |grep -o -m 100 '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}')
Also read user000001's answer. The missing echo when getting the output is another issue.

Resources