Some Changes To Make Here In This Tlc Script - scripting

Now the script is work great, but need to change the commands and remove channel name, when i add IP in exemp.txt file list,
someone can help here, how to change this public comand , thx in advance
!exemp help change in !help
!exemp list change in !list
!exemp del 1 change in !del 75.34.37.12 75.34.37.* 75.34.*
!exemp add change in !add 75.34.37.12 75.34.37.* 75.34.*
and to remove the name channel when i add Ip on exemp.txt list
to add only the IP cozz is added and channel name with Ip on file exemp.txt
#Test 75.34.37.12
thank you in advance
proc check_ip {ip} {
set file [open "exemp.txt" r]
set fdata [split [read $file] \n]
close $file
foreach entry $fdata {
if {[string match $entry $ip]} {
return 1
}
}
return 0
}
bind pub n|n !exemp exemp:cmd
set exemp(file) "exemp.txt"
if {![file exists $exemp(file)]} {
set file [open $exemp(file) w]
close $file
}
proc exemp:cmd {nick host hand chan arg} {
global exemp
set arg0 [lindex [split $arg] 0]
set arg1 [lindex [split $arg] 1]
if {$arg0 == ""} {
putserv "NOTICE $nick :EXEMP Use: \002!exemp help\002 for more informations."
return
}
switch $arg0 {
add {
if {$arg1 == ""} {
putserv "NOTICE $nick :EXEMP Use: \002!exemp help\002 for more informations."
return
}
set file [open $exemp(file) a]
puts $file "$chan $arg1"
close $file
putserv "NOTICE $nick :EXEMP I added\002 $arg1 \002in my ExempList."
}
list {
set file [open $exemp(file) "r"]
set read [read -nonewline $file]
close $file
set data [split $read "\n"]
set i 0
if {$data == ""} {
putserv "NOTICE $nick :EXEMP There are\002 no IP \002added to ExempList."
return
}
putserv "NOTICE $nick :EXEMP The list of IP added in my ExempList."
foreach line $data {
set read_chan [lindex [split $line] 0]
if {[string match -nocase $read_chan $chan]} {
set i [expr $i +1]
set read_blackchan [lindex [split $line] 1]
putserv "NOTICE $nick :$i.) $read_blackchan"
}
}
}
del {
array set exempdel [list]
if {![regexp {.*?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*?\((.*?)\)} $arg1]} {
putserv "NOTICE $nick :EXEMP Use: \002!exemp help\002 for more informations."
return
}
set file [open $exemp(file) "r"]
set data [read -nonewline $file]
close $file
set lines [split $data "\n"]
set counter -1
set line_counter -1
set current_place -1
foreach line $lines {
set line_counter [expr $line_counter + 1]
set read_chan [lindex [split $line] 0]
if {[string match -nocase $read_chan $chan]} {
set counter [expr $counter + 1]
set exempdel($counter) $line_counter
}
}
foreach place [array names exempdel] {
if {$place == [expr $arg1 - 1]} {
set current_place $exempdel($place)
}
}
if {$current_place == "-1"} {
putserv "NOTICE $nick :EXEMP The entry number\002 $arg1 \002does not exist."
return
}
set delete [lreplace $lines $current_place $current_place]
set files [open $exemp(file) "w"]
puts $files [join $delete "\n"]
close $files
set file [open $exemp(file) "r"]
set data [read -nonewline $file]
close $file
if {$data == ""} {
set files [open $exemp(file) "w"]
close $files
}
putserv "NOTICE $nick :EXEMP The entry number\002 $arg1 \002was removed from ExempList."
}
help {
putserv "NOTICE $nick :EXEMP You can add IP using: \002!exemp add <IP>\002 "
putserv "NOTICE $nick :EXEMP To see all the IP in ExempList use:\002 !exemp list\002"
putserv "NOTICE $nick :EXEMP To delete a IP use:\002 !exemp del <number>\002 (from the ExempList)"
}
}
}
How is work now
<BoB> !exemp add 75.34.37.12
TestBot EXEMP I added 75.34.37.12 in my ExempList.
<BoB> !exemp list
TestBot EXEMP The list of IP added in my ExempList.
TestBot 1.) 75.34.37.12
<BoB> !exemp del 1
TestBot EXEMP The entry number 1 was removed from ExempList.
<BoB> !exemp list
TestBot EXEMP There are no IP added to ExempList.
<BoB> !exemp del 75.34.37.12
TestBot EXEMP Use: !exemp help for more informations.
<BoB> !exemp help
TestBot EXEMP You can add IP using: !exemp add <IP>
TestBot EXEMP To see all the IP in ExempList use: !exemp list
TestBot- EXEMP To delete a IP use: !exemp del <number> (from the ExempList}

Related

How to return a reference value with a method from an extended Powershell object?

I'm trying to extend a Powershell object with a method that
returns a true or false to indicate success
outputs a value by reference ([ref])
I have in my module MyExtensions.psm1.
Update-TypeData -TypeName [MyType] -MemberType ScriptMethod -memberName TryGetValue -force -value `
{
param(
$myInput,
[ref]$myOutput
)
try
{
# do something with $myInput
$myOutput = …
return $true
}
catch
{
return $false
}
}
The goal is to be able to write in a script or in another module:
Import-Module MyExtensions
$myInput = …
$value = $null
if($myTypeItem.TryGetValue($myInput, $value)
{
# I know that the $value is good
}
Using argument by reference (you just miss $myOutput.Value ="")
function addition ([int]$x, [int]$y, [ref]$R)
{
$Res = $x + $y
$R.value = $Res
}
$O1 = 1
$O2 = 2
$O3 = 0
addition $O1 $O2 ([ref]$O3)
Write-Host "values from addition $o1 and $o2 is $o3"
A more comple answer here.

checking cell value in csv and formatting in HTML using awk

#!/usr/bin/awk -f
BEGIN {
FS=","
print "<table>"
}
{
gsub(/</, "\\<")
gsub(/>/, "\\>")
gsub(/&/, "\\>")
print "\t<tr>"
for(f = 1; f <= NF; f++) {
if(NR == 1 && header) {
printf "\t\t<th>%s</th>\n", $f
}
else printf "\t\t<td>%s</td>\n", $f
}
print "\t</tr>"
}
END {
print "</table>"
}
how to check value of $f inside loop if cell value contains "No" then how to print using
printf("<TD class=AltGreen align=right height="17" width="5%">%s</TD>\n",$f)
instead of printf "\t\t<td>%s</td>\n", $f
Input.csv
USA,NO,45
UK,YES,90*
I have made a couple of changes to your original logic in Awk
To remove the empty spaces from the $f fields, while parsing in a loop
Include check for $f to string NO
The Awk code I use as follows,
#!/usr/bin/awk -f
BEGIN {
FS=","
print "<table>"
}
{
gsub(/</, "\\<")
gsub(/>/, "\\>")
gsub(/&/, "\\>")
print "\t<tr>"
for(f = 1; f <= NF; f++) {
gsub(/ /, "", $f)
if(NR == 1 && header) {
printf "\t\t<th>%s</th>\n", $f
}
else if ( $f == "NO" ) {
printf "\t\t<TD class=AltGreen align=right height=\"17\" width=\"5%\">%s</TD>\n",$f
}
else printf "\t\t<td>%s</td>\n", $f
}
print "\t</tr>"
}
END {
print "</table>"
}
produced an output as
<table>
<tr>
<td>USA</td>
<TD class=AltGreen align=right height="17" width="5%">NO</TD>
<td>45</td>
</tr>
<tr>
<td>UK</td>
<td>YES</td>
<td>90*</td>
</tr>
</table>
#!/usr/bin/awk -f
BEGIN {
#header = 1
# for the no in OP and NO in sample
IGNORECASE = 1
FS=","
print "<table>"
}
{
gsub(/</, "\\<")
gsub(/>/, "\\>")
gsub(/&/, "\\>")
print "\t<tr>"
for(f = 1; f <= NF; f++) {
if(NR == 1 && header) {
printf "\t\t<th>%s</th>\n", $f
}
else {
# your NO filtering
if ( $f ~ /^NO$/) {
printf("<TD class=AltGreen align=right height=\"17\" width=\"5%\">%s</TD>\n", $f)
else {
printf "\t\t<td>%s</td>\n", $f
}
}
}
print "\t</tr>"
}
END {
print "</table>"
}
i just modify a bit your code to keep it the most as you do.
use $f ~ //
I add IGNORECASE, 0 for case sensitive, 1 not
adapt your double quote for quoted value of HTML output
Some remarks:
I think you want to replace gsub(/&/, "\\>") with gsub(/&/, "\\&").
You do not need header when you check on NR.
When you want to check on "NO" in the header too, you can do something like
echo "USA,NO,45
UK,YES,90*" | awk '
BEGIN {
FS=","
print "<table>"
}
{
gsub(/</, "\\<")
gsub(/>/, "\\>")
gsub(/&/, "\\&")
print "\t<tr>"
if(NR==1) {
tag="th"
} else {
tag="td"
}
for (f = 1; f <= NF; f++) {
if ( $f =="NO") {
printf("<%s class=AltGreen align=right height=\"17\" width=\"5%%\">%s</%s>\n",
tag, $f, tag)
} else {
printf "\t\t<%s>%s</%s>\n", tag, $f, tag
}
}
print "\t</tr>"
}

Pretty print a TCL list

Having a TCL list that looks like below (formatted for better visibility):
set mylist [list \
"title_1 title_2 title_3 " \
"row1col1_bla row1col2 row1col3 " \
"r2c1 r2c2_blablabla r2c3" \
"r3c1_really_long_string r3c2 r3c3" \
]
I need a procedure that prints $mylist like:
title_1 title_2 title_3
1) row1col1_bla row1col2 row1col3
2) r2c1 &FN_1 r2c3
3) &FN_2 r3c2 r3c3
Footnotes:
FN_1: r2c2_blablabla
FN_2: r3c1_really_long_string
The procedure should take as input:
COLMAXLEN: the maximum length of any individual string from $mylist, beyound which that string will go to the Footnotes section (being replaced by the $SHORTCUT_$index value)
SHORTCUT: string that replaces any individual member of $mylist, if its length is greater than $COLMAXLEN.
The following function does exactly this. Are there any suggestions to possibly simplify or improve it?
#!/usr/bin/tclsh
set COLMAXLEN 12
set SHORTCUT "FN"
proc puts_list {mylist} {
global COLMAXLEN SHORTCUT
set num_row [llength $mylist]
set num_col [llength [lindex $mylist 0]]
set ref_list {}
# Define/init col_width (a list having $num_col elements)
set col_width {}
for {set col 0} {$col < $num_col} {incr col} {
lappend col_width 0
}
# Get the max width of each column AND
# replace the elements > $COLMAXLEN with footnote shortcuts!
for {set row 0} {$row < $num_row} {incr row} {
set new_row {}
for {set col 0} {$col < $num_col} {incr col} {
set myrow [lindex $mylist $row]
set myitem [lindex $myrow $col]
set mysize [string length $myitem]
if { $mysize > $COLMAXLEN } {
lappend ref_list $myitem
set myitem "&[subst $SHORTCUT]_[llength $ref_list]"
set mysize [string length $myitem]
}
if { $mysize > [lindex $col_width $col] } {
lset col_width $col $mysize
}
lappend new_row $myitem
}
lset mylist $row $new_row
}
# Start printing
set num_col_width [expr [string length $num_row] +1]
puts ""
for {set row 0} {$row < $num_row} {incr row} {
if { $row == 0 } {
puts -nonewline [format "%[subst $num_col_width]s" { }]
} else {
puts -nonewline [format "%[subst $num_col_width]s" "$row)"]
}
puts -nonewline " "
for {set col 0} {$col < $num_col} {incr col} {
set myrow [lindex $mylist $row]
set myitem [lindex $myrow $col]
set mysize [expr [lindex $col_width $col] +1]
puts -nonewline [format "%-[subst $mysize]s" $myitem]
}
puts ""
}
puts ""
puts " Footnotes:"
set ref_num [llength $ref_list]
for {set i 0} {$i < $ref_num} {incr i} {
puts " [subst $SHORTCUT]_[format %-[subst [string length $ref_num]]s [expr $i + 1]]: [lindex $ref_list $i]"
}
puts ""
}
ASSUMPTION: TCL version is 8.4
# Print the row number
proc put_row_number {rowNumber} {
if {$rowNumber == 0} {
puts -nonewline " "
} else {
puts -nonewline "$rowNumber) "
}
}
proc put_table {table {colmaxlen 12} {shortcut FN}} {
set ref {}
set refCount 0
set rowCount 0
foreach row $table {
put_row_number $rowCount
incr rowCount
foreach cell $row {
if {[string length $cell] > $colmaxlen} {
incr refCount
set key "${shortcut}_${refCount}"
lappend ref $key $cell
set cell "&$key"
}
puts -nonewline [format "%-*s " $colmaxlen $cell]
}
puts ""
}
puts "\n Footnotes:"
foreach {key value} $ref {
puts " $key: $value"
}
}
set mylist {
"title_1 title_2 title_3 "
"row1col1_bla row1col2 row1col3 "
"r2c1 r2c2_blablabla r2c3"
"r3c1_really_long_string r3c2 r3c3"
}
put_table $mylist

Powershell incremental number at start of string

Attempting to increment the start of a string with a number.
foreach ($var in $variables) {
New-EventLog -computername $PC -LogName $var -source $var
}
I wish to increment $var with a number, so the result is like so:
$var = 1Server
$var = 2Server
etc etc.
How do I add in incremental number at the beginning of $var in my foreach statement?
I tried with:
$a = 1
foreach ($var in $variables) {
New-EventLog -computername $PC -LogName ($a++, $var) -source $var
}
But no dice.
You can use the format operator -f to insert the value of $a in the parameter for the Logname
$a = 1
foreach ($var in $variables) {
New-EventLog -computername $PC -LogName ("{0}$var" -f $a++) -source $var
}

how to edit .htpasswd using php?

i have a protected directory where only user on .htpasswd can access, but sometimes it requires the user to change password or username, edit a specific username password to his username him self
sample users
kevien : kka
mike : mike
And let say i want to change kevien to XYZ
And same thing goes to password
I have modified function to use all types of crypt alghoritms. Someone may find it useful:
/*
Function change password in htpasswd.
Arguments:
$user > User name we want to change password to.
$newpass > New password
$type > Type of cryptogrphy: DES, SHA, MD5.
$salt > Option: Add your custom salt (hashing string).
Salt is applied to DES and MD5 and must be in range 0-9A-Za-z
$oldpass > Option: Add more security, user must known old password to change it.
This option is not supported for DES and MD5 without salt!!!
$path > Path to .htaccess file which contain the password protection.
Path to password file is obtained from this .htaccess file.
*/
function changePass($user, $newpass, $type="SHA", $salt="", $oldpass="", $path=".htaccess")
{
switch ($type) {
case "DES" :
$salt = substr($salt,0,2); // Salt must be 2 char range 0-9A-Za-z
$newpass = crypt($newpass,$salt);
if ($oldpass != null) {
$oldpass = crypt($oldpass,$salt);
}
break;
case "SHA" :
$newpass = '{SHA}'.base64_encode(sha1($newpass, TRUE));
if ($oldpass != null) {
$oldpass = '{SHA}'.base64_encode(sha1($oldpass, TRUE));
}
break;
case "MD5" :
$salt = substr($salt,0,8); //Salt must be max 8 char range 0-9A-Za-z
$newpass = crypt_apr1_md5($newpass, $salt);
if ($oldpass != null) {
$oldpass = crypt_apr1_md5($oldpass, $salt);
}
break;
default:
return false;
break;
}
$hta_arr = explode("\n", file_get_contents($path));
foreach ($hta_arr as $line) {
$line = preg_replace('/\s+/','',$line); // remove spaces
if ($line) {
$line_arr = explode('"', $line);
if (strcmp($line_arr[0],"AuthUserFile") == 0) {
$path_htaccess = $line_arr[1];
}
}
}
$htp_arr = explode("\n", file_get_contents($path_htaccess));
$new_file = "";
foreach ($htp_arr as $line) {
$line = preg_replace('/\s+/', '', $line); // remove spaces
if ($line) {
list($usr, $pass) = explode(":", $line, 2);
if (strcmp($user, $usr) == 0) {
if ($oldpass != null) {
if ($oldpass == $pass) {
$new_file .= $user.':'.$newpass."\n";
} else {
return false;
}
} else {
$new_file .= $user.':'.$newpass."\n";
}
} else {
$new_file .= $user.':'.$pass."\n";
}
}
}
$f = fopen($path_htaccess,"w") or die("couldn't open the file");
fwrite($f, $new_file);
fclose($f);
return true;
}
Function for generating Apache like MD5:
/**
* #param string $password
* #param string|null $salt
* #ref https://stackoverflow.com/a/8786956
*/
function crypt_apr1_md5($password, $salt = null)
{
if (!$salt) {
$salt = substr(base_convert(bin2hex(random_bytes(6)), 16, 36), 1, 8);
}
$len = strlen($password);
$text = $password . '$apr1$' . $salt;
$bin = pack("H32", md5($password . $salt . $password));
for ($i = $len; $i > 0; $i -= 16) {
$text .= substr($bin, 0, min(16, $i));
}
for ($i = $len; $i > 0; $i >>= 1) {
$text .= ($i & 1) ? chr(0) : $password[0];
}
$bin = pack("H32", md5($text));
for ($i = 0; $i < 1000; $i++) {
$new = ($i & 1) ? $password : $bin;
if ($i % 3) {
$new .= $salt;
}
if ($i % 7) {
$new .= $password;
}
$new .= ($i & 1) ? $bin : $password;
$bin = pack("H32", md5($new));
}
$tmp = '';
for ($i = 0; $i < 5; $i++) {
$k = $i + 6;
$j = $i + 12;
if ($j == 16) {
$j = 5;
}
$tmp = $bin[$i] . $bin[$k] . $bin[$j] . $tmp;
}
$tmp = chr(0) . chr(0) . $bin[11] . $tmp;
$tmp = strtr(
strrev(substr(base64_encode($tmp), 2)),
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
);
return "$" . "apr1" . "$" . $salt . "$" . $tmp;
}
Demo of crypt_apr1_md5() is available here.
Note that as of Apache 2.4, bcrypt is supported, so you can (and SHOULD) just use password_hash() on newer versions of Apache for this purpose.
Ofc this is just a sample, that will read your current file, find the given username and change either it is password of username.
Please keep in mind that this code is not safe and you would still need to parse the username and password so it does not break your file.
$username = $_POST['user'];
$password = $_POST['pass'];
$new_username = $_POST['newuser'];
$new_password = $_POST['newpass'];
$action = $_POST['action'];
//read the file into an array
$lines = explode("\n", file_get_contents('.htpasswd'));
//read the array and change the data if found
$new_file = "";
foreach($lines as $line)
{
$line = preg_replace('/\s+/','',$line); // remove spaces
if ($line) {
list($user, $pass) = split(":", $line, 2);
if ($user == $username) {
if ($action == "password") {
$new_file .= $user.':'.$new_password."\n";
} else {
$new_file .= $new_username.':'.$pass."\n";
}
} else {
$new_file .= $user.':'.$pass."\n";
}
}
}
//save the information
$f=fopen(".htpasswd","w") or die("couldn't open the file");
fwrite($f,$new_file);
fclose($f);
Don't. Store your authdb in a database instead, via e.g. mod_auth_mysql.
Googled "php generate htpasswd", got this article: How to create a password for a .htpasswd file using PHP.
The key line seems to be:
$password = crypt($clearTextPassword, base64_encode($clearTextPassword));
So I imagine you'd read in the file contents with file_get_contents, parse it into an associative array, modify the relevant entries (encrypting the password as shown above), write the array back into a string, and use file_put_contents to write the file back out.
This is most definitely not standard practice, however. Sounds like the job for a database. If you feel weird about setting up a whole database server, and your host supports it, SQLite might be a good choice.
Just in case someone is just looking for a working script, here is a solution.
It is the script published here by Kavoir with a minor change: http://www.kavoir.com/backyard/showthread.php?28-Use-PHP-to-generate-edit-and-update-htpasswd-and-htgroup-authentication-files
<?php
/*
$pairs = array(
'username' = 'password',
);
*/
// Algorithm: SHA1
class Htpasswd {
private $file = '';
public function __construct($file) {
if (file_exists($file)) {
$this -> file = $file;
} else {
return false;
}
}
private function write($pairs = array()) {
$str = '';
foreach ($pairs as $username => $password) {
$str .= "$username:{SHA}$password\n";
}
file_put_contents($this -> file, $str);
}
private function read() {
$pairs = array();
$fh = fopen($this -> file, 'r');
while (!feof($fh)) {
$pair_str = str_replace("\n", '', fgets($fh));
$pair_array = explode(':{SHA}', $pair_str);
if (count($pair_array) == 2) {
$pairs[$pair_array[0]] = $pair_array[1];
}
}
return $pairs;
}
public function addUser($username = '', $clear_password = '') {
if (!empty($username) && !empty($clear_password)) {
$all = $this -> read();
// if (!array_key_exists($username, $all)) {
$all[$username] = $this -> getHash($clear_password);
$this -> write($all);
// }
} else {
return false;
}
}
public function deleteUser($username = '') {
$all = $this -> read();
if (array_key_exists($username, $all)) {
unset($all[$username]);
$this -> write($all);
} else {
return false;
}
}
public function doesUserExist($username = '') {
$all = $this -> read();
if (array_key_exists($username, $all)) {
return true;
} else {
return false;
}
}
private function getHash($clear_password = '') {
if (!empty($clear_password)) {
return base64_encode(sha1($clear_password, true));
} else {
return false;
}
}
}
You can use this script like:
$htp = new Htpasswd('.htpasswd');
$htp -> addUser('username1', 'clearpassword1'); // this will add or edit the user
$htp -> deleteUser('username1');
// check if a certain username exists
if ($htp -> doesUserExist('username1')) {
// user exists
}