In the void is virtue, and no evil. Wisdom has existance, principle has existance, the Way has existance, spirit is nothingness.
Image
Search This Blog
Tuesday, January 18, 2011
Install Windows printers
' VBScript - Silently remove ALL network printers, install new ones with default
' this script require 2 additional files: one defining the printers we need to
' install, one printer per line and a second file defining what default printer
' we use, depending on what IP range this computer belongs the format of this
' file is IP_Range, Default_Printer (IP_Range is defined as, ex: 10.0.IP_Range.9)
' -----------------------------------------------------------------------'
Dim printer, sServer, i, l, default
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objNet = CreateObject("WScript.Network")
Set WshShell = CreateObject("WScript.Shell")
Set wmiLocator = CreateObject("WbemScripting.SWbemLocator")
Set wmiNameSpace = wmiLocator.ConnectServer(objNet.ComputerName, "root\default")
Set objRegistry = wmiNameSpace.Get("StdRegProv")
Const HKEY_CLASSES_ROOT = &H80000000
Const HKEY_CURRENT_USER = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
Const HKEY_USERS = &H80000003
strComputer = "."
'Define the server where printers reside
sServer = "\\sqlsrv"
'If the OS is win7 we need to install printers from a win 2008 server
Set objWMIService = GetObject("winmgmts:" &_
"{impersonationLevel=impersonate}!\\" & strComputer & _
"\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
if objOperatingSystem.Caption = "Microsoft Windows 7 " then sServer = "\\2k8srv"
'wscript.echo sServer
Next
' If this script alredy run once for this user, then EXIT
userprrf = WshShell.Environment("PROCESS")("UserProfile")
'wscript.Echo userprrf
If (objFSO.FileExists(userprrf & "\sctwashere.txt")) Then
Wscript.Quit
Else
blah = "let's have some fun"
End If
' Deletes RegistryKey with all subkeys in Network printers
sPath = "Printers\Connections"
lRC = DeleteRegEntry(HKEY_CURRENT_USER, sPath)
Function DeleteRegEntry(sHive, sEnumPath)
' Attempt to delete key. If it fails, start the subkey enumration process.
lRC = objRegistry.DeleteKey(sHive, sEnumPath)
' The deletion failed, start deleting subkeys.
If (lRC <> 0) Then
' Subkey Enumerator
On Error Resume Next
lRC = objRegistry.EnumKey(HKEY_CURRENT_USER, sEnumPath, sNames)
For Each sKeyName In sNames
If Err.Number <> 0 Then Exit For
lRC = DeleteRegEntry(sHive, sEnumPath & "\" & sKeyName)
Next
On Error Goto 0
' At this point we should have looped through all subkeys, trying to delete the key again.
lRC = objRegistry.DeleteKey(sHive, sEnumPath)
End If
End Function
'Now let's recreate the "root" Key we deleted before
objRegistry.CreateKey HKEY_CURRENT_USER,sPath
'Tell something to the user
'with createobject("wscript.shell")
' .popup "All Printers are now erased, Reinstalling...",5, "Printers Manager"
'end with
'Let's see in what ip range we are, so we can choose a default printer
Set objWMIService = GetObject( _
"winmgmts:\\" & strComputer & "\root\cimv2")
Set IPConfigSet = objWMIService.ExecQuery _
("Select IPAddress from Win32_NetworkAdapterConfiguration ")
For Each IPConfig in IPConfigSet
If Not IsNull(IPConfig.IPAddress) Then
For i=LBound(IPConfig.IPAddress) _
to UBound(IPConfig.IPAddress)
strArray=Split(IPConfig.IPAddress(i),".")
if ubound(strArray) > 2 Then
'WScript.Echo strArray(2)
if strArray(0) = 192 And strArray(1) = 168 Then
Exit For
End if
End If
Next
End If
Next
' Read the file containig the pair ip-range, default-printer
'(the ip range is the 3rd digit in the ip - 10.0.X.3 - gives X as range)
Set objFile = objFSO.OpenTextFile("defaultlist.txt", ForReading)
'WScript.Echo strArray(2)
Do Until objFile.AtEndOfStream
defaultArray = split(objFile.ReadLine,",")
if defaultArray(0) = strArray(2) Then
defaultprt=defaultArray(1)
'wscript.Echo defaultArray(1)
exit do
end if
Loop
objFile.Close
default = sServer & "\" & defaultArray(1)
'wscript.Echo default
'Now let's start installing the printers listed in plist.txt
Set objFile = objFSO.OpenTextFile("plist.txt", ForReading)
Do Until objFile.AtEndOfStream
printer = objFile.ReadLine
printer = sServer & "\" & printer
if printer = default then
strCmd = "rundll32 printui.dll,PrintUIEntry /in /n """ & printer & """ /u /q /Gw"
WshShell.Run strCmd,,true
strCmd = "rundll32 printui.dll,PrintUIEntry /y /n """ & printer & ""
else
strCmd = "rundll32 printui.dll,PrintUIEntry /in /n """ & printer & """ /u /q /Gw"
end if
WshShell.Run strCmd
Loop
objFile.Close
with createobject("wscript.shell")
.popup "All Printers Are Now ReInstalled",15, "Printers Management"
end with
'We're done, let's leave a trace in userprofile, so at next login this script will exit
Set objFile1 = objFSO.CreateTextFile(userprrf & "\sctwashere.txt")
Wscript.Quit
Saturday, January 15, 2011
Monitor windows logs
Considering that Intel's Matrix Raid does not have a way to send emails
in case of a HDD failure, I've searched for a way of monitoring the
Windows system log and send a mail in case of an event. The monitoring
part can be solved with a simple vbs script (made by splattne), this
script being run as service by the "Non-Sucking Service Manager"
( http://iain.cx/src/nssm/ ).
You can define the events you want to be alerted on, in the vbs script
with the "PushEventToMonitor" call. The arguments are: event ID, event
log name, source, category, type, user, and a regular expression that
can be matched against the log message. We have an example in the vbs
script that matches the start / stop of the TELNET service, as well as
one that will match the startup of the script itself (which logs an
event out to the Application Log) and a real case for Intel MatrixRaid.
In order to install the service, run in a command prompt: "nssm install
SimpleEventLogMonitor" and in the following window choose
"%SystemRoot%\System32\cscript.exe" as Application and
"c:\Path\to\eventmonitor.vbs" as Option.
To uninstall run: "nssm remove SimpleEventLogMonitor confirm" (Warning:
you can uninstall any service with this command!)
vbs script starts here:
Option Explicit
' Main
Dim objShell, objWMIService, objEventSink, dictEventsToMonitor, eventToMonitor
' =====================( Configuration )=====================
' Set to 0 to disable event log reporting of bans / unbans
Const USE_EVENTLOG = 0
Const EVENTLOG_SOURCE = "SimpleEventMonitor"
' SMTP configuration
Const EMAIL_SENDER = "EventLogMonitor@xxxxxxxxxxxx.ca"
Const EMAIL_RECIPIENT = "sorin@xxxxxxxx.com"
Const EMAIL_SMTP_SERVER = "relais.xxxxxxxxxx.ca"
Const EMAIL_SMTP_PORT = 25
Const EMAIL_TIMEOUT = 20
Set dictEventsToMonitor = CreateObject("Scripting.Dictionary")
' Define events that should be monitored. Matches are based on exact matches of all non-NULL fields
' Order: event ID, event log name, source, category, type, user, and a regular expression
'PushEventToMonitor "100", "Application", EVENTLOG_SOURCE, NULL, NULL, NULL, NULL
'PushEventToMonitor "7036", "System", "Service Control Manager", NULL, NULL, NULL, "Telnet service.*(running|stopped).*state"
' Monitor my Intel service
PushEventToMonitor "7202", "System", " IAANTmon", NULL, "Warning", NULL, NULL
' ===================( End Configuration )===================
Set objShell = CreateObject("WScript.Shell")
' Create event sink to catchevents
Set objWMIService = GetObject("winmgmts:{(security)}!root/cimv2")
Set objEventSink = WScript.CreateObject("WbemScripting.SWbemSink", "eventSink_")
objWMIService.ExecNotificationQueryAsync objEventSink, "SELECT * FROM __InstanceCreationEvent WHERE TargetInstance ISA 'Win32_NTLogEvent'"
' Loop sleeping for one week, logging an event each week to say we're still alive
While (True)
LogEvent 100, "INFORMATION", "Simple Event Log Monitor started"
WScript.Sleep(7 * 24 * 60 * 60 * 1000)
Wend
' Fires each time new events are generated
Sub eventSink_OnObjectReady(objEvent, objWbemAsyncContext)
Dim evt, field, boolAlert, regexpMessage
For Each evt In dictEventsToMonitor.Keys
boolAlert = True
For Each field In dictEventsToMonitor.Item(evt).Keys
If UCase(Field) = "MESSAGE" Then
Set regexpMessage = new Regexp
regexpMessage.Pattern = dictEventsToMonitor.Item(evt).Item(Field)
regexpMessage.IgnoreCase = True
If NOT regexpMessage.Test(objEvent.TargetInstance.Properties_(Field)) then boolAlert = False
Else
If UCase(objEvent.TargetInstance.Properties_(Field)) <> UCase(dictEventsToMonitor.Item(evt).Item(field)) Then boolAlert = False
End If
Next ' field
if boolAlert = True Then
SendMessage "Simple Event Log Monitor notification from " & objEvent.TargetInstance.ComputerName, _
"Event ID: " & objEvent.TargetInstance.EventCode & VbCrLf _
& "Date/Time: " & Mid(objEvent.TargetInstance.TimeGenerated, 5, 2) & "/" & Mid(objEvent.TargetInstance.TimeGenerated, 7, 2) & "/" & Mid(objEvent.TargetInstance.TimeGenerated, 1, 4) & " " & Mid(objEvent.TargetInstance.TimeGenerated, 9, 2) & ":" & Mid(objEvent.TargetInstance.TimeGenerated, 11, 2) & ":" & Mid(objEvent.TargetInstance.TimeGenerated, 13, 2) & VbCrLf _
& "Computer: " & objEvent.TargetInstance.ComputerName & vbCrLf _
& "Event Log: " & objEvent.TargetInstance.LogFile & vbCrLf _
& "Event Source: " & objEvent.TargetInstance.SourceName & vbCrLf _
& "Event Category: " & objEvent.TargetInstance.CategoryString & vbCrLf _
& "Event Type: " & objEvent.TargetInstance.Type & vbCrLf _
& "User Name: " & objEvent.TargetInstance.User & vbCrLf _
& "Message:" & vbCrLf & vbCrLF _
& objEvent.TargetInstance.Message
Exit Sub
End If
Next ' evt
End Sub
Sub LogEvent(ID, EventType, Message)
' Log an event to the Windows event log
If USE_EVENTLOG Then objShell.Exec "EVENTCREATE /L APPLICATION /SO " & EVENTLOG_SOURCE & " /ID " & ID & " /T " & EventType & " /D """ & Message & """"
End Sub
Sub SendMessage(strSubject, strBody)
Dim objCDOMessage
Set objCDOMessage = CreateObject("CDO.Message")
objCDOMessage.From = EMAIL_SENDER
objCDOMessage.To = EMAIL_RECIPIENT
objCDOMessage.Subject = strSubject
objCDOMessage.Textbody = strBody
objCDOMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = EMAIL_SMTP_SERVER
objCDOMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = EMAIL_SMTP_PORT
objCDOMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = EMAIL_TIMEOUT
objCDOMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objCDOMessage.Configuration.Fields.Update
objCDOMessage.send
End Sub
Sub PushEventToMonitor(strID, strLog, strSource, strCategory, strType, strUser, strMessagePattern)
Dim x
x = dictEventsToMonitor.Count
Set dictEventsToMonitor.Item(x) = CreateObject("Scripting.Dictionary")
If NOT IsNull(strID) Then dictEventsToMonitor.Item(x).Add "EventCode", strID
If NOT IsNull(strLog) Then dictEventsToMonitor.Item(x).Add "LogFile", strLog
If NOT IsNull(strSource) Then dictEventsToMonitor.Item(x).Add "SourceName", strSource
If NOT IsNull(strCategory) Then dictEventsToMonitor.Item(x).Add "CategoryString", strCategory
If NOT IsNull(strType) Then dictEventsToMonitor.Item(x).Add "Type", strType
If NOT IsNull(strType) Then dictEventsToMonitor.Item(x).Add "User", strUser
If NOT IsNull(strMessagePattern) Then dictEventsToMonitor.Item(x).Add "Message", strMessagePattern
End Sub
Friday, August 27, 2010
Print to fax
#!/usr/bin/perl -w
# This perl script routes postscript printerdata from printerspooler to fax
#
# copy to /usr/lib/cups/backends/ and run this script from the commandline: echo blah | ./netfax
# it will tell if there are any dependancies unsolved: this tool is dependant upon the following:
# perl (we tested with v5.6 and its likely any v5 will do)
# perl modules Getopt-Long-2.32 and Mail-Sendmail-0.78
# sendfax (from the hylafax package)
# ps2ascii ps2pdf pdf2ps (comes with the ghostscript package)
# pdftk http://www.accesspdf.com/pdftk/
# a mask.pdf file that will hide the command parameters sent at the begining of your page by overlaying a white image
#
# After that you can add new printer to cups: lpadmin -p NetFax -E -v netfax.pl:
# Share the printer in samba and, if your fax server joined the domain, run:
# net -S localhost -U administrator rpc rights grant 'administrator' SePrintOperatorPrivilege
# in smb.conf [printers] section add -J %m to print command (tipically: lpr-cups -P %p -J %m -o raw $s)
# or add cups option = "%m" in the same section and make the drivers share [print$] writable
# Now from windows machine browse the fax server printers, right-click NetFax, choose properties,
# say NO when asked to install drivers, go to Advanced tab, and choose "New Driver". Choose
# some plain PS printer line Apple LaserWriter 12/640 PS and push the drivers to server.
# Now your printer can now be install on all workstations by a vbs script or by using printUI.dll.
#
# The accepted commands, placed at the begining of your faxed document are:
# 'Fax-Nr : XXX-XXXXX;(XXX)XXXXX~' the number can contain dashes or paranthesis. multiple numbers are separated by ;
# 'Clientid : AAAAAA AAAA~' the recipient name
# 'Subjectid : AAAA AAAAAAA~' the message subject
# 'E-m@il : AAA@BBBBBBB~' sender's email. if BBBBBBB matches a different windows machine name
# a winpopup message will be sent to that machine instead of originating machine
#
# Please note that every command line ends by a ~ character!
#
# in order to send a winpopup message add the following lines to notify_mail() function in /var/spool/fax/bin/notify
# HST = `echo $2 | sed -e 's/[^>]*@\([^ ]*\).*/\1/' -e '2.$d'`
# echo $1 | /usr/bin/smbclient -M $HST
#
# neXt - sorin@xxxxxxxx.com - June-2010
#
use strict;
use Getopt::Long;
use Mail::Sendmail;
# constants you must check if they are ok
my $ALLOWMULTIFAX = 1; # allow (1) or not (0) multiple faxdestinations
my $EMAILFROMDOC = 1; # get the emailaddress from samba (0) or the doc (1)
my $SENDFAX = "/usr/bin/sendfax"; # the command to send a fax
my $PS2ASCII = "/usr/bin/ps2ascii"; # the command to convert postscript to readable text
my $PS2PDF = "/usr/bin/ps2pdf"; # transform ps to pdf
my $PDFTK = "/usr/bin/pdftk"; # modify pdfs - used to overlay the mask over commands section
my $PDF2PS = "/usr/bin/pdf2ps"; # transform pdf back to ps
my $WATERMARK = "/etc/initsetup/mask.pdf"; # location of the overlay mask
# constants you can alter but should consider not to
my $TMPDIR = "/tmp/"; # the directory to store temporary files
my $MYNAME = "netfax"; # the name of this tool
my $LOGFILE = $TMPDIR . $MYNAME . ".log"; # the name of the logfile - debugging sessions only
my $PSFILE = $TMPDIR . $MYNAME . $$ . ".ps" ; # the name of the postscript temporary file
my $PSTMPFILE = $TMPDIR . $MYNAME . $$ . "work.ps" ; # the name of the postscript temporary file
my $MAILADDRESS = 'faxadmin@hfax'; # the default mailaddress for errormessages
my $MULTISEP = ";"; # if you have more than 1 faxnr on a line, they are seperated by ;
# this character should NOT appear in $DIGITS
my $DEBUG=0;
# constants you really should not touch !!!
my $FAXID = 'Fax-Nr[s]{0,1}\s*:\s*'; # search string for fax-nr
my $FAXIDS = 'Fax-Nrs\s*:\s*'; # search string for fax-nrs ( for multifax }
my $DIGITS = '0123456789+( ),-'; # digits allowed in the faxnr
my $MODEMLIKES = '0123456789+,'; # digits my modem will not reject: ,=wait +=int.access
# this should be a subset of $DIGITS
my $EMAILDOC = 'E-m@il :'; # the string to look for an emailaddress
my $CLIENTID = 'Clientid :'; # this is the recipient name
my $SUBJECTID = 'Subjectid :'; # the line with subject must contain this
########## from here on, leave the code alone, unless you are really sure ############
#variables
my @faxlines; # stores the raw faxlines
my @faxdest; # stores the faxnumbers
my $MultiFax = 0; # determines if ENDuser specified to multifax
my $mailaddress = ""; # how do we treat the errormessages
my $lpuser = ""; # username retrieved from lprng or lpd commandline
my $lphost = ""; # hostname retrieved from lprng or lpd commandline
my $client = " "; # the client name
my $subject = " "; # the message subject
my @emaillines; # stores the documentlines containing EMAILDOC
my @clienthost; # stores the temporary sender hostname
my @clientline; # stores the client name line
my @subjectline; # stores the subject line
#Check for arguments - if none, cups is initialising
if (@ARGV == 0) {
exit 0;
}
# check some dependencies
if ( ! -d $TMPDIR ) {
print("Error: temporary directory not found: ", $TMPDIR );
exit 1;
}
if ( ! -e $SENDFAX ) {
Log("Error: sendfax command not found: ", $SENDFAX );
exit 1;
}
if ( ! -e $PS2ASCII ) {
Log("Error: ghostscript command not found: ", $PS2ASCII );
exit 1;
}
# get usefull parameters
my $cupsfile = $ARGV[5]; # CUPS parses a filename with the printdata as the 6th parameer
# this could be undef (after lpr -d blah) or a filename (after a samba action)
my $cupsuser = $ARGV[1]; # CUPS paresed the username with the printdata as the 2nd parameter
# this is usually a user from localhost
GetOptions( 'h=s' => \$lphost, # LPD and LPRng parse host and user name under the -h and -n parameter
'n=s' => \$lpuser); # the postscript is parsed to it in a pipe - to be found in STDIN
my $fullhost = $ARGV[4]; #hostname is found here because in smb.conf I've added -P %m on print command
# let's extract the hostname in order to be added to email address
@clienthost = split(/\s+/,$fullhost);print $clienthost[0];
my $finalhost = $clienthost[0];
# ok lets find out where we can send the mail to
if ( ( $lphost ) and ( $lpuser ) ) { #if the user and host can be found on the commandline
$mailaddress = $lpuser . '@' . $lphost ;
} elsif ( $cupsuser) {
$mailaddress = $cupsuser . '@' . $finalhost ; # create "email" from user+hostname
} else {
$mailaddress = $MAILADDRESS; # or use the E-m@il defined in doc
}
# where is the printerdata?
if ( ( $cupsfile ) and ( -e $cupsfile ) ) {
$PSFILE = $cupsfile;
} else {
&SavePostscriptdata;
}
if ($DEBUG) {
Log("");
Log("------------------------------------------");
Log("");
}
# ok we have a postscriptfile, now
if ( &RetrieveRawFaxline ) { # we found one ore more lines
if ( &ExtractFaxnumber ) { # we could extract a real faxnumber
$client = &GetClientFromDoc; # get the Client Id
$subject = &GetSubjectFromDoc; # Get the Subject
if ($EMAILFROMDOC) {
$mailaddress = &GetEmailFromDoc; # Get the email from doc
}
if ($DEBUG) {
Log("Debug: email address = ",$mailaddress);
Log("Debug: postscript file = ",$PSFILE);
Log("Debug: cups file = ",$cupsfile);
}
&TrySending; # mask the header and send the fax
} else { # no real faxnumber could be extracted
&SendErrorMail;
Log("No Fax Number extracted");
}
} else { # no lines with faxnr found
&SendErrorMail;
Log("No Fax-Nr found");
}
# delete the temporary printfiles in case DEBUG is off
if (!$DEBUG) {
unlink $PSFILE;
unlink $PSTMPFILE;
unlink $PSTMPFILE . ".pdf";
unlink $PSTMPFILE . "clean.pdf";
}
Log("End of task");
# always exit gracefully.
exit 0;
# sub #################################################
# save the information in the pipe to the ps tmp file
sub SavePostscriptdata {
Log("sub SavePostscriptData");
open PS, ">".$PSFILE or die("Sorry, cannot open temporary postscript file $PSFILE .\n");
while (
print PS $_ ;
}
close PS;
}
# sub #################################################
sub RetrieveRawFaxline {
my $CL = $PS2ASCII . " " . $PSFILE . " |";
my $ret = 0;
open CL, $CL; # carry out ps2ascii on the ps-file and return the output into perl
while (my $line=
chomp $line;
if ($line =~ /$FAXID/i) { # if the rawline matches with fax-nr
push @faxlines, $line ; # add it to the stack of matching lines
$ret++;
}
if ($line =~ /$FAXIDS/i) { # if the rawline matches with fax-nrs
$MultiFax = 1; # the userties to multifax
}
if ($line =~ /$CLIENTID/i) { # if the rawline matches with clientid
push @clientline, $line ; # add it to the stack of matching lines
if ($DEBUG) {
Log("Debug: clientline added - ",$line);
}
}
if ($line =~ /$SUBJECTID/i) { # if the rawline matches with subjectid
push @subjectline, $line ; # add it to the stack of matching lines
if ($DEBUG) {
Log("Debug: subjectline added - ",$line);
}
}
if ($line =~ /$EMAILDOC/i) { # if the rawline matches with "email"
push @emaillines, $line; # add it to the emailstack
if ($DEBUG) {
Log("Debug: emailline added - ",$line);
}
}
}
close CL;
# check the multifax setting
$MultiFax = $ALLOWMULTIFAX if $MultiFax; # ALLOWMULTIFAX overrides Multifax
return $ret;
}
# sub #################################################
sub ExtractFaxnumber {
my $ret = 0; # return value: 0=nothing found, more=ok
if ( $MultiFax ) { # extract all the faxnumbers you can find
for ( my $i=0; $i<@faxlines; $i++) { # for all the rawline push @faxdest, &GetFaxNumbersFrom($faxlines[$i]); #extract the numbers } $ret = @faxdest; } else { # just extract the first faxnumber in the first line my @fns = &GetFaxNumbersFrom($faxlines[0]); # extract the numbers from the first raw line if ( defined $fns[0] ) { # if it exists push @faxdest, $fns[0]; # put it on the return stack $ret++; } } return $ret; } # sub ################################################# sub GetFaxNumbersFrom { my @ret = (); my $rawline = shift; if ( defined $rawline ) { my $ModemRejects = "[^" . $MODEMLIKES . "]"; # regexp with non-modem chars if ( $rawline =~ /$FAXIDS/i ) { #line contains fax-nrs $rawline =~ s/$FAXID/;/gi ; # substitute all the Fax-Nr with an ; my @fnrs = split(/;/, $rawline); # split the line up between non-allowed digits for ( my $i=0; $i<@fnrs; $i++) { # for all the splitups my $f = $fnrs[$i]; my $goodpart = '([' . $DIGITS . ']*)[^' . $DIGITS . ']*.*$'; $f =~ s/$goodpart/$1/ ; # keep the goodpart $f =~ s/$ModemRejects//g; # remove all the non-modem characters if ( $f gt "" ) { # and if anything is left push @ret, $f; # add it to the return stack } } } else { # if we find a faxnr, take special care my $re = '^.*' . $FAXID; # search for fax-nr $re .= "("; $re .= "[" . $DIGITS . "]*"; # followed by allowed digits $re .= ")"; $re .= "[^" . $DIGITS . ']*.*$'; # followed by non-allowed digits $rawline =~ s/$re/$1/i ; # and extract the allowed part from it $rawline =~ s/$ModemRejects//g; # then remove all the non-modem characters if ( $rawline gt "" ) { # and if anything is left push @ret, $rawline; # add it to the return stack } } } return @ret; } # sub ################################################# sub GetEmailFromDoc { my $result = $mailaddress; # the default return is the existing mailaddress if (@emaillines > 0) { # if there are any emailsadresses found
# take the 1st found only, ignore the rest
# anything after the : is the emailaddress
#(undef, my $em) = split(/$EMAILDOC/, $emaillines[0]);
(undef, my $em1) = split(/$EMAILDOC/, $emaillines[0]);
#Log("pre space em1=",$em1);
# remove trailing and leading spaces
$em1 =~ s/^\s+//, $em1 =~ s/\s+$//;
# $em1 =~ s/^\s*(\S*)\s*$/$1/;
if ($DEBUG) {
Log("Debug: post space strip em1=",$em1);
}
# Log(" second split of em1=",$em1);
(my $em, my $em2) = split(/~/,$em1);
if ($DEBUG) {
Log("Debug: final em = ",$em);
}
# if there is a @ in the middle consider the email address valid
if ($em =~ /\w+@\w+/) {
$result = $em;
}
}
return $result;
}
# sub #################################################
sub GetClientFromDoc {
my $result = $client; # the default return is the existing client name
if (@clientline > 0) { # if there are any client lines found
# take the 1st found only, ignore the rest
# anything after the : is the clientname
#(undef, my $em) = split(/$EMAILDOC/, $emaillines[0]);
(undef, my $cl1) = split(/$CLIENTID/, $clientline[0]);
#Log("pre space cl1=",$cl1);
# remove trailing and leading spaces
$cl1 =~ s/^\s+//, $cl1 =~ s/\s+$//;
# $cl1 =~ s/^\s*(\S*)\s*$/$1/;
if ($DEBUG) {
Log("Debug: post space strip cl1=",$cl1);
}
# The line ends at ~
(my $cl, my $cl2) = split(/~/,$cl1);
if ($DEBUG) {
Log("Debug: final cl = ",$cl);
}
$result = $cl;
}
return $result;
}
# sub #################################################
sub GetSubjectFromDoc {
my $result = $subject; # the default return is the existing subject
if (@subjectline > 0) { # if there are any subject lines found
# take the 1st found only, ignore the rest
# anything after the : is the subject
(undef, my $su1) = split(/$SUBJECTID/, $subjectline[0]);
#Log("pre space su1=",$su1);
# remove trailing and leading spaces.
$su1 =~ s/^\s+//, $su1 =~ s/\s+$//;
# $su1 =~ s/^\s*(\S*)\s*$/$1/;
if ($DEBUG) {
Log("Debug: post space strip su1=",$su1);
}
# The line ends at ~
(my $su, my $su2) = split(/~/,$su1);
if ($DEBUG) {
Log("Debug: final su = ",$su);
}
$result = $su;
}
return $result;
}
# sub #################################################
sub TrySending {
for ( my $i=0; $i<@faxdest; $i++ ) { # for every found faxnumber # compile a commandline # check if file exists if (-e $PSFILE) { my $fcp = "cp " . $PSFILE . " " . $PSTMPFILE; system $fcp; } # transform to pdf, my $pspdf = $PS2PDF . " " . $PSTMPFILE . " " . $PSTMPFILE . ".pdf"; system $pspdf; # execute if ($DEBUG) { # and log it Log($pspdf); } # apply mask, my $wmark = $PDFTK . " " . $WATERMARK . " background " . $PSTMPFILE . ".pdf output " . $PSTMPFILE . "clean.pdf"; system $wmark; #execute if ($DEBUG) { # and log it Log($wmark); } # transform back to ps my $pdfps = $PDF2PS . " " . $PSTMPFILE . "clean.pdf " . $PSFILE; system $pdfps; # execute if ($DEBUG) { # and log it Log($pdfps); } # now send the fax my $fc = $SENDFAX . " -n -R -f " . $mailaddress . " -i \"" . $subject . "\" -d \"" . $client . "@" . $faxdest[$i] . "\" " . $PSFILE ; # my $fc = $SENDFAX . " -n -D -f " . $mailaddress . " -d " . $faxdest[$i] . " " . $PSFILE ; system $fc; # execute it if ($DEBUG) { # and log it Log($fc); } } } # sub ################################################# sub SendErrorMail { my $mh = "\n"; $mh .= "The faxnumber is not recognized in your fax of " . localtime() . "\n"; $mh .= "\n"; $mh .= "The faxnumber is recognised via this text:\n"; $mh .= " Fax-Nr :
$mh .= "\n";
if ( $ALLOWMULTIFAX ) {
$mh .= " or\n";
$mh .= " Fax-Nrs :
$mh .= "\n";
}
$mh .= "The 'Fax-Nr' part is not case sensitive.\n";
$mh .= "The characters allowed in the
$mh .= "\n";
$mh .= "Please correct and retry.\n";
sendmail( To => $mailaddress ,
From => 'Your hylafax gateway
Subject => 'Your facsimile request failed.',
Message => $mh
);
Log("sent errormail to $mailaddress");
}
# sub #################################################
sub Log {
open LG, ">>" . $LOGFILE;
print LG join(" ", @_), "\n";
close LG;
}
Saturday, June 19, 2010
Replacing a failing software raid drive in 10 easy steps
1 - cat /proc/mdstat and check for referrences to failing device
(sda = first sata hdd, sdb = the second one, so on...) the failed
partition should be something like /dev/sdb5 (I'm goin to refer to this
partition as /dev/sdYn and I'm going to call the good one /dev/sdXn)
2 - fdkisk -l /dev/sdX (where sdX is the GOOD hdd); fdisk -l /dev/sdY
- take a note of all partition configuration
3 - remove failed hdd: mdadm --manage /dev/md0 --fail /dev/sdYn ;
mdadm --manage /dev/md0 --remove /dev/sdYn (/dev/sdYn is the failed device!)
4 - phisically replace hdd (maybe with a shutdown before? :-) )
5 - sfdisk -d /dev/sdX | sfdisk /dev/sdY will create identical partitions
on the new hdd, similar to the ones on the good hdd (usually a /boot
of 100MB as primary partition and the rest as extended type FD "Linux
raid autodetect")
6 - check if the partitions are identical: fdkisk -l /dev/sdY
(compare with what you read at step 2)
7 - mdadm --manage /dev/md0 --add /dev/sdYn will add the new
partition tothe raid array
8 - watch the rebuid procedure: watch -n 10 cat /proc/mdstat (if
you are bored type ^C - the rebuid is done anyway)
9 - in order to make a copy of the boot partition too, do a mount
/dev/sdY1 /boot2 (the first partition is usually the 100MB /boot), then
do acd /boot ; find . -depth -print | cpio -padmV /boot2 ; grub-install /dev/sdY
10 - enjoy a beer, you have a working raid again!
Saturday, March 13, 2010
Spamfilter 2.0 - teoria initiala
Sigur, am si parti bune in 1.x, pe care le voi copia in v2, printre care: autoupdate/push updates, remote services monitoring, redir, call-home licensing...
Voi pastra combinatia postfix-spamassassin ca si structura de baza, dar proabil ca voi muta toata configuratia si storage-ul intr-o baza de date. Bazat pe scriptul de getuser probabil, voi crea o metoda autentificare a userilor la serverul principal de mail daca e exchange, iar pentru un server unix va trebui sa descopar cum imi pot autentifica userii la serverul pop3 - in felul asta nu am nevoie de alte combinatii user/parola pentru managementul mesajelor in carantina.
Trebuie sa fie posibil sa transfer bazele de date postgey si baesyan (actualmente berkleydb) in noul sistem, pen' ca sigur o sa trebuiasca sa upgradez din vechile sisteme sia ar fi bine sa pastrez rata mare de detectie pe care o am deja.
Trebuie sa investighez daca nu cumva cramfs/alt_filesystem_read_only in combinatie cu unionfs nu e o solutie mai buna pentru SSD-uri sau USB-flashuri (care actualmente sunt super-lente, iar pe masini cu >1mil de spamuri/luna crapa execrabil cu ext3fs chiar daca am mutat /tmp in ram si am limitat drastic scrierile pe disk).
Ca o ultima idee ar fi sa mut /etc/initsetup-ul intr-o interfata web, scapand astfel de nevoia initiala de a avea kbd+screen pentru instatalare si permitandu-mi poate sa modific cutia in ceva gen router cu doar un port rj45, un powercord si un powerbutton.
Edit: beta 1 is out! working on bug fixes now.
Edit2: spamfilter2, codename "miserable failure" is retired. let's welcome SpamFilter3!
Sunday, February 14, 2010
Laptop brightness
#include
void usage()
{
fprintf(stderr, "Usage: lcd-brightness [value]\n");
}
int main(int argc, char *argv[])
{
FILE *fp;
int bright = 0;
const char *kFileName =
"/sys/class/backlight/acpi_video0/brightness";
switch (argc) {
case 1:
fp = fopen(kFileName, "r");
fscanf(fp, "%d", &bright);
printf("%d\n", bright);
break;
case 2:
fp = fopen(kFileName, "w");
bright = atoi(argv[1]);
fprintf(fp, "%d\n", bright);
break;
default:
usage();
return -1;
}
fclose(fp);
return 0;
}
sa-l salvam undeva in path cu numele brightness si acum putem mapa niste taste in kde care sa-l apeleze:

Iar ca si command scriem:
brightness $(expr $(brightness) - 1); kdialog
--passivepopup "Decrease Brightness to `cat
/sys/class/backlight/acpi_video0/brightness`" 1
- asta va da un frumos notification pop-up cand este apelat:

Evident, trebuie mapata o combinatie si pentru Brightness up, care va face +1 in loc de -1 in comanda.
Sunday, February 07, 2010
Another Backup
#!/bin/sh # @(#) AUTOTBACK 2.8 09/12/09 # # 09/12/2009 (sorin@xxxxxxxx.com) mod for debian5. remove hit report. changed to use TAR # 28/08/2008 (sorin@xxxxxxxx.com) modified for rhel5. skip /proc /sys /tmp # modified 9/14/2000 to provide hit reporting on web site # # Usage -Command to be incorporated in cron of root for off Peak # automatic system TAR Backup. # Generates report in /var/autotback directory, mail and prints it. # # ####### Define Local Variables ################ RECIPIENT1=service@xxxxxxxx.com RECIPIENT2=sorin@xxxxxxxx.com PRINTER=HP4050 TAPE=/dev/st0 BACKDIR=/ EXCLUDE=/sys/* EXCLUDE1=/proc/* EXCLUDE2=/dev/* EXCLUDE3=/var/run/* EXCLUDE4=/tmp/* ############################################### # System variables LOCK=/var/autotback/backlock DEFAULTDIR=/var/autotback REPORTFILE=/var/autotback/backrep TEMPFILE=/var/autotback/backtmp TEMPFILE2=/var/autotback/backtmp2 ALLIST=/var/autotback/allist LIST=/var/autotback/list ERRORMSG="Another backup is running or the last backup has not finished well. Please check" DELIMIT="================================================================================" # define a remove lock and set a trap on exit remove_lock() { rm -f $LOCK } # make sure we release the lock no matter how we exit, when we exit trap remove_lock 0 # Check if another backup is running or if the script crashed in such way that the lock is still there, clear the lock if [ -r $LOCK ] then DIFF=`echo "\`date +%s\`-\`cat $LOCK\`" | bc` if [ $DIFF -gt 86400 ]; then echo "More than one day since backup is NOT running, autoclean..." >> $REPORTFILE; rm -f $LOCK; fi sed -i -e "1i\ $ERRORMSG" -e "1i\ $DELIMIT" -e "1i\ " $REPORTFILE echo $ERRORMSG >> $REPORTFILE echo $REPORTFILE | mail -s "Backup Failure on $HOSTNAME" $RECIPIENT1 $RECIPIENT2 lp -d $PRINTER $REPORTFILE exit 5 fi # Cleanup obsolete traces cd $BACKDIR rm -rf $DEFAULTDIR if [ ! -d $DEFAULTDIR ] then mkdir -p $DEFAULTDIR fi # Create lockfile echo "`date +%s`">$LOCK # Start backup echo " Automatic Backup Report (c)1991-2010 Xxxxxxxx Xxxxxxxxx Inc. $DELIMIT Backup of $BACKDIR on $HOSTNAME started at `date` ">>$REPORTFILE # Create a list of what we have to backup and exclude #cd $BACKDIR #find . -depth -print >$ALLIST #grep -vE ".$EXCLUDE|.$EXCLUDE1|.$EXCLUDE2|.$EXCLUDE3|.$EXCLUDE4" $ALLIST >$LIST echo "BACKUP started on `date`">$TEMPFILE # Start saving at the begining of the tape mt -f $TAPE rewind 2>>$TEMPFILE2 #cat $LIST | cpio -ocvB >$TAPE 2>>$TEMPFILE tar --exclude=$EXCLUDE --exclude=$EXCLUDE1 --exclude=$EXCLUDE2 --exclude=$EXCLUDE3 --exclude=$EXCLUDE4 -cvpf $TAPE $BACKDIR >>$TEMPFILE 2>>$TEMPFILE2 backstat=$? tail $TEMPFILE2 >>$REPORTFILE echo " Exit status = $backstat ">>$REPORTFILE if [ $backstat -eq 0 ] then echo "*** Backup COMPLETED OK ***">>$REPORTFILE fi if [ $backstat -eq 1 ] then echo "*** Backup may be incomplete or have missing files ***">>$REPORTFILE fi if [ $backstat -eq 2 ] then echo "*** Backup has encounter a fatal error. Please check ***">>$REPORTFILE fi echo "Tape Save finished on `date` $DELIMIT ">>$REPORTFILE # Check total nr of blocks reported by cpio #set `tail -1 $TEMPFILE` #BACKTOT=$1 #echo "Total of amount of Backup was $1 blocks. echo "Verify of $BACKDIR on $HOSTNAME started at `date` ">>$REPORTFILE # Tape rewind / Verify mt -f $TAPE rewind 2>>$TEMPFILE2 # cpio -icvtB <$TAPE >>$TEMPFILE 2>>$TEMPFILE2 tar --exclude=$EXCLUDE --exclude=$EXCLUDE1 --exclude=$EXCLUDE2 --exclude=$EXCLUDE3 --exclude=$EXCLUDE4 --exclude=$EXCLUDE -tpvf $TAPE >>$TEMPFILE 2>>$TEMPFILE2 verstat=$? tail $TEMPFILE2 >>$REPORTFILE echo " Exit status = $verstat ">>$REPORTFILE if [ $verstat -eq 0 ] then echo "*** Verify COMPLETED OK *** ">>$REPORTFILE if [ $verstat -eq 1 ] then echo "*** Verify may be incomplete *** ">>$REPORTFILE if [ $verstat -eq 2 ] then echo "*** Verify has encounter a fatal error. Please check *** ">>$REPORTFILE cat $TEMPFILE >> $REPORTFILE fi echo "Tape Verify finished on `date` ">>$REPORTFILE # Check nr of verified blocks reported by cpio and send warning if not ok #set `tail -1 $TEMPFILE2` #VERTOT=$1 #if [ "$BACKTOT" != "$VERTOT" -o $backstat -ne 0 -o $verstat -ne 0 ] #then # echo "*** WARNING BACKUP TRANSFER TOTALS DID NOT MATCH ***">>$REPORTFILE # echo "*** PLEASE VERIFY *** # ">>$REPORTFILE #else # echo "*** Transfer Totals Concur *** # ">>$REPORTFILE #fi echo $DELIMIT >>$REPORTFILE # Send / Print the report cat $REPORTFILE | mail -s "Backup Report $HOSTNAME" $RECIPIENT1 $RECIPIENT2 lp -d $PRINTER $REPORTFILE # Remove lock, eject and exit sleep 5 rm -f $LOCK mt -f $TAPE rewoffl 2>>$TEMPFILE2 exit 0
Sunday, January 10, 2010
Thursday, December 10, 2009
Fax setup
#!/bin/bash
# greetings from neXt :)
#cd /etc/initsetup
vardt=/etc/initsetup/vardt
log=/etc/initsetup/setup.log
if [ -f $log ]; then
oldexp=`grep expd $log | cut -d= -f2`
fi
. $vardt
echo -en "Starting setup: " > $log
date > $log
cat $vardt >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 1/10" \
--inputbox "Enter your domain name" 8 60 $fakedom 2>/tmp/input.$$
sel=$?
dom=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo dom=$dom >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 2/10" \
--inputbox "Enter your IP address" 8 60 $fakeip 2>/tmp/input.$$
sel=$?
ipif=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipif=$ipif >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 3/10" \
--inputbox "Enter the MailServer IP address" 8 60 $fakemail 2>/tmp/input.$$
sel=$?
ipmail=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipmail=$ipmail >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 4/10" \
--inputbox "Enter the Gateway IP address" 8 60 $fakegw 2>/tmp/input.$$
sel=$?
ipgw=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipgw=$ipgw >> $log
diafucklog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 5/10" \
--inputbox "Enter the DNS IP address" 8 60 $fakedns 2>/tmp/input.$$
sel=$?
ipdns=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipdns=$ipdns >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 6/10" \
--inputbox "Enter the Range of IP address" 8 60 $fakenet 2>/tmp/input.$$
sel=$?
ipnet=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipnet=$ipnet >> $log
/bin/sed -i s/$fakedom/$dom/g /etc/hosts
/bin/sed -i s/$fakedom/$dom/g /etc/squirrelmail/config.php
/bin/sed -i s/$fakedom/$dom/g /etc/postfix/transport
/bin/sed -i s/$fakedom/$dom/g /etc/sysconfig/network
/bin/sed -i s/$fakedom/$dom/g /etc/postfix/main.cf
/bin/sed -i s/$fakeip/$ipif/g /etc/sysconfig/network-scripts/ifcfg-eth0
/bin/sed -i s/$fakeip/$ipif/g /etc/initsetup/getbackup
/bin/sed -i s/$fakedns/$ipdns/g /etc/resolv.conf
/bin/sed -i s/$fakedns/$ipdns/g /etc/sysconfig/network-scripts/ifcfg-eth0
/bin/sed -i s^$fakenet^$ipnet^g /etc/postfix/main.cf
/bin/sed -i s/$fakemail/$ipmail/g /etc/postfix/transport
/bin/sed -i s/$fakemail/$ipmail/g /etc/postfix/main.cf
/bin/sed -i s/$fakegw/$ipgw/g /etc/sysconfig/network
/bin/sed -i s/$fakegw/$ipgw/g /etc/sysconfig/network-scripts/ifcfg-eth0
echo -en "Files modified, restarting network..."
/sbin/service network restart >> $log
echo -en " Wait a second, network config still active..."
sleep 10
echo "Changing default route" >> $log
/sbin/route del default
/sbin/route add default gw $ipgw
export HOSTNAME=HFAX.$dom
cp -f /etc/inittab.nofax /etc/inittab.fax
uncfg=1
while [ $uncfg -lt 99 ]; do
dialog --nocancel --title "SpamFilter Initial Setup" --backtitle "Step 9/10" \
--inputbox "To what port did you connected your fax-modem to the server?" 10 40 $fakeport 2>/tmp/input.$$
sel=$?
port=`cat /tmp/input.$$`
rm -f /tmp/input.$$
fakeport=$port
echo port=$port >> $log
case $sel in
0) cp -f /etc/inittab.nofax /etc/inittab
/sbin/init q
killall faxgetty
faxsetup
/sbin/service hylafax-server stop
killall faxq
sleep 5
faxaddmodem $port
if cat /var/spool/fax/etc/config.$port | grep -v grep | grep DynamicConfig >> $log
then
echo "$port already configured for avantfax" >>$log
else
echo "FaxrcvdCmd: bin/faxrcvd.php
DynamicConfig: bin/dynconf.php
UseJobTSI: true" >> /var/spool/fax/etc/config.$port
fi
if cat /etc/inittab.fax | grep -v grep | grep 'respawn:/usr/sbin/faxgetty $port' >> $log
then
echo "$port already configured for receiving" >>$log
else
echo "m$uncfg:2345:respawn:/usr/sbin/faxgetty $port" >> /etc/inittab.fax
fi
let uncfg++
sleep 5
/sbin/service hylafax-server start
cp -f /etc/inittab.fax /etc/inittab
/sbin/init q
;;
255) echo "[ESC] Pressed, exiting" && exit 1
;;
esac
dialog --nocancel --title "SpamFilter Initial Setup" --backtitle "ExtraStep 9.1/10" \
--yes-label End --no-label Add_Modem \
--yesno "Did you finished, or there are still modems connected?" 10 40
sel=$?
case $sel in
0) uncfg=999
;;
255) echo "[ESC] Pressed, exiting" && exit 1
;;
esac
done
echo > $vardt
echo fakedom=$dom >> $vardt
echo fakeip=$ipif >> $vardt
echo fakemail=$ipmail >> $vardt
echo fakegw=$ipgw >> $vardt
echo fakedns=$ipdns >> $vardt
echo fakenet=$ipnet >> $vardt
echo fakeport=$port >> $vardt
echo >> $vardt
echo -en "Last step: Restarting services..."
/etc/init.d/run
/sbin/service hylafax-server restart 1>>$log 2>&1
/sbin/service postfix restart 1>>$log 2>&1
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 9/10" \
--msgbox "Let's add users for the fax now. point a browser to http://HFAX/admin login as
admin with the usual password, go to 'NewUser'.
Don't forget to go also to Configure Modems and to setup the default fax-to-email recipient!
Then, from each client, browse the network to \\HFAX\public folder#!/bin/bashig/network-scripts/ifcfg-eth0
# greetings from neXt :)
#cd /etc/initsetup
vardt=/etc/initsetup/vardt
log=/etc/initsetup/setup.log
if [ -f $log ]; then
oldexp=`grep expd $log | cut -d= -f2`
fi
. $vardt
echo -en "Starting setup: " > $log
date > $log
cat $vardt >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 1/10" \
--inputbox "Enter your domain name" 8 60 $fakedom 2>/tmp/input.$$
sel=$?
dom=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo dom=$dom >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 2/10" \
--inputbox "Enter your IP address" 8 60 $fakeip 2>/tmp/input.$$
sel=$?
ipif=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipif=$ipif >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 3/10" \
--inputbox "Enter the MailServer IP address" 8 60 $fakemail 2>/tmp/input.$$
sel=$?
ipmail=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipmail=$ipmail >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 4/10" \
--inputbox "Enter the Gateway IP address" 8 60 $fakegw 2>/tmp/input.$$
sel=$?
ipgw=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipgw=$ipgw >> $log
diafucklog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 5/10" \
--inputbox "Enter the DNS IP address" 8 60 $fakedns 2>/tmp/input.$$
sel=$?
ipdns=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipdns=$ipdns >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 6/10" \
--inputbox "Enter the Range of IP address" 8 60 $fakenet 2>/tmp/input.$$
sel=$?
ipnet=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipnet=$ipnet >> $log
/bin/sed -i s/$fakedom/$dom/g /etc/hosts
/bin/sed -i s/$fakedom/$dom/g /etc/squirrelmail/config.php
/bin/sed -i s/$fakedom/$dom/g /etc/postfix/transport
/bin/sed -i s/$fakedom/$dom/g /etc/sysconfig/network
/bin/sed -i s/$fakedom/$dom/g /etc/postfix/main.cf
/bin/sed -i s/$fakeip/$ipif/g /etc/sysconfig/network-scripts/ifcfg-eth0
/bin/sed -i s/$fakeip/$ipif/g /etc/initsetup/getbackup
/bin/sed -i s/$fakedns/$ipdns/g /etc/resolv.conf
/bin/sed -i s/$fakedns/$ipdns/g /etc/sysconfig/network-scripts/ifcfg-eth0
/bin/sed -i s^$fakenet^$ipnet^g /etc/postfix/main.cf
/bin/sed -i s/$fakemail/$ipmail/g /etc/postfix/transport
/bin/sed -i s/$fakemail/$ipmail/g /etc/postfix/main.cf
/bin/sed -i s/$fakegw/$ipgw/g /etc/sysconfig/network
/bin/sed -i s/$fakegw/$ipgw/g /etc/sysconfig/network-scripts/ifcfg-eth0
echo -en "Files modified, restarting network..."
/sbin/service network restart >> $log
echo -en " Wait a second, network config still active..."
sleep 10
echo "Changing default route" >> $log
/sbin/route del default
/sbin/route add default gw $ipgw
export HOSTNAME=HFAX.$dom
cp -f /etc/inittab.nofax /etc/inittab.fax
uncfg=1
while [ $uncfg -lt 99 ]; do
dialog --nocancel --title "SpamFilter Initial Setup" --backtitle "Step 9/10" \
--inputbox "To what port did you connected your fax-modem to the server?" 10 40 $fakeport 2>/tmp/input.$$
sel=$?
port=`cat /tmp/input.$$`
rm -f /tmp/input.$$
fakeport=$port
echo port=$port >> $log
case $sel in
0) cp -f /etc/inittab.nofax /etc/inittab
/sbin/init q
killall faxgetty
faxsetup
/sbin/service hylafax-server stop
killall faxq
sleep 5
faxaddmodem $port
if cat /var/spool/fax/etc/config.$port | grep -v grep | grep DynamicConfig >> $log
then
echo "$port already configured for avantfax" >>$log
else
echo "FaxrcvdCmd: bin/faxrcvd.php
DynamicConfig: bin/dynconf.php
UseJobTSI: true" >> /var/spool/fax/etc/config.$port
fi
if cat /etc/inittab.fax | grep -v grep | grep 'respawn:/usr/sbin/faxgetty $port' >> $log
then
echo "$port already configured for receiving" >>$log
else
echo "m$uncfg:2345:respawn:/usr/sbin/faxgetty $port" >> /etc/inittab.fax
fi
let uncfg++
sleep 5
/sbin/service hylafax-server start
cp -f /etc/inittab.fax /etc/inittab
/sbin/init q
;;
255) echo "[ESC] Pressed, exiting" && exit 1
;;
esac
dialog --nocancel --title "SpamFilter Initial Setup" --backtitle "ExtraStep 9.1/10" \
--yes-label End --no-label Add_Modem \
--yesno "Did you finished, or there are still modems connected?" 10 40
sel=$?
case $sel in
0) uncfg=999
;;
255) echo "[ESC] Pressed, exiting" && exit 1
;;
esac
done
echo > $vardt
echo fakedom=$dom >> $vardt
echo fakeip=$ipif >> $vardt
echo fakemail=$ipmail >> $vardt
echo fakegw=$ipgw >> $vardt
echo fakedns=$ipdns >> $vardt
echo fakenet=$ipnet >> $vardt
echo fakeport=$port >> $vardt
echo >> $vardt
echo -en "Last step: Restarting services..."
/etc/init.d/run
/sbin/service hylafax-server restart 1>>$log 2>&1
/sbin/service postfix restart 1>>$log 2>&1
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 9/10" \
--msgbox "Let's add users for the fax now. point a browser to http://HFAX/admin login as
admin with the usual password, go to 'NewUser'.
Don't forget to go also to Configure Modems and to setup the default fax-to-email recipient!
Then, from each client, browse the network to \\HFAX\public folder and install ghostscript and yajhfc.
Start YajHFC, setup credentials and choose the coverpage from \\HFAX\public\cover.ps" 20 60
sel=$?
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Final info" \
--infobox "The system config and variables are backed-up daily in /etc/initsetup/backup.tgz. In order to save the backup on the unix machine just use the /etc/initsetup/getbackup ftp commands file.
Copy the file to the unix server (you can do that by ftp: as ftpuser:trsf on this box) get /tmp/getbackup /some/path/to/getbackup) and add the following line to cron:
50 21 * * * ftp -n /dev/null
If the server is windows, use the same getbackup script, started daily at 21:50 from getbackup.cmd via Task Scheduler.
THIS IS THE END OF SETUP (see logs in setup.log)" 20 60
sel=$?
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
echo "Welcome to FaxServer" > /etc/motd
echo "DONE!"
exit 0
/bin/sed -i s^$fakenet^$ipnet^g /etc/postfix/main.cf
/bin/sed -i s/$fakemail/$ipmail/g /etc/postfix/transport
/bin/sed -i s/$fakemail/$ipmail/g /etc/postfix/main.cf
/bin/sed -i s/$fakegw/$ipgw/g /etc/sysconfig/network
/bin/sed -i s/$fakegw/$ipgw/g /etc/sysconfig/network-scripts/ifcfg-eth0
echo -en "Files modified, restarting network..."
/sbin/service network restart >> $log
echo -en " Wait a second, network config still active..."
sleep 10
echo "Changing default route" >> $log
/sbin/route del default
/sbin/route add default gw $ipgw
export HOSTNAME=HFAX.$dom
cp -f /etc/inittab.nofax /etc/inittab.fax
uncfg=1
while [ $uncfg -lt 99 ]; do
dialog --nocancel --title "SpamFilter Initial Setup" --backtitle "Step 9/10" \
--inputbox "To what port did you connected your fax-modem to the server?" 10 40 $fakeport 2>/tmp/input.$$
sel=$?
port=`cat /tmp/input.$$`
rm -f /tmp/input.$$
fakeport=$port
echo port=$port >> $log
case $sel in
0) cp -f /etc/inittab.nofax /etc/inittab
/sbin/init q
killall faxgetty
faxsetup
/sbin/service hylafax-server stop
killall faxq
sleep 5
faxaddmodem $port
if cat /var/spool/fax/etc/config.$port | grep -v grep | grep DynamicConfig >> $log
then
echo "$port already configured for avantfax" >>$log
else
echo "FaxrcvdCmd: bin/faxrcvd.php
DynamicConfig: bin/dynconf.php
UseJobTSI: true" >> /var/spool/fax/etc/config.$port
fi
if cat /etc/inittab.fax | grep -v grep | grep 'respawn:/usr/sbin/faxgetty $port' >> $log
then
echo "$port already configured for receiving" >>$log
else
echo "m$uncfg:2345:respawn:/usr/sbin/faxgetty $port" >> /etc/inittab.fax
fi
let uncfg++
sleep 5
/sbin/service hylafax-server start
cp -f /etc/inittab.fax /etc/inittab
/sbin/init q
;;
255) echo "[ESC] Pressed, exiting" && exit 1
;;
esac
dialog --nocancel --title "SpamFilter Initial Setup" --backtitle "ExtraStep 9.1/10" \
--yes-label End --no-label Add_Modem \
--yesno "Did you finished, or there are still modems connected?" 10 40
sel=$?
case $sel in
0) uncfg=999
;;
255) echo "[ESC] Pressed, exiting" && exit 1
;;
esac
done
echo > $vardt
echo fakedom=$dom >> $vardt
echo fakeip=$ipif >> $vardt
echo fakemail=$ipmail >> $vardt
echo fakegw=$ipgw >> $vardt
echo fakedns=$ipdns >> $vardt
echo fakenet=$ipnet >> $vardt
echo fakeport=$port >> $vardt
echo >> $vardt
echo -en "Last step: Restarting services..."
/etc/init.d/run
/sbin/service hylafax-server restart 1>>$log 2>&1
/sbin/service postfix restart 1>>$log 2>&1
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 9/10" \
--msgbox "Let's add users for the fax now. point a browser to http://HFAX/admin login as
admin with the usual password, go to 'NewUser'.
Don't forget to go also to Configure Modems and to setup the default fax-to-email recipient!
Then, from each client, browse the network to \\HFAX\public folder and install ghostscript and yajhfc.
Start YajHFC, setup credentials and choose the coverpage from \\HFAX\public\cover.ps" 20 60
sel=$?
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Final info" \
--infobox "The system config and variables are backed-up daily in /etc/initsetup/backup.tgz. In order to save the backup on the unix machine just use the /etc/initsetup/getbackup ftp commands file.
Copy the file to the unix server (you can do that by ftp: as ftpuser:trsf on this box) get /tmp/getbackup /some/path/to/getbackup) and add the following line to cron:
50 21 * * * ftp -n /dev/null
If the server is windows, use the same getbackup script, started daily at 21:50 from getbackup.cmd via Task Scheduler.
THIS IS THE END OF SETUP (see logs in setup.log)" 20 60
sel=$?
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
echo "Welcome to FaxServer" > /etc/motd
echo "DONE!"
exit 0
#!/bin/bash
# greetings from neXt :)
#cd /etc/initsetup
vardt=/etc/initsetup/vardt
log=/etc/initsetup/setup.log
if [ -f $log ]; then
oldexp=`grep expd $log | cut -d= -f2`
fi
. $vardt
echo -en "Starting setup: " > $log
date > $log
cat $vardt >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 1/10" \
--inputbox "Enter your domain name" 8 60 $fakedom 2>/tmp/input.$$
sel=$?
dom=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo dom=$dom >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 2/10" \
--inputbox "Enter your IP address" 8 60 $fakeip 2>/tmp/input.$$
sel=$?
ipif=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipif=$ipif >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 3/10" \
--inputbox "Enter the MailServer IP address" 8 60 $fakemail 2>/tmp/input.$$
sel=$?
ipmail=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipmail=$ipmail >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 4/10" \
--inputbox "Enter the Gateway IP address" 8 60 $fakegw 2>/tmp/input.$$
sel=$?
ipgw=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipgw=$ipgw >> $log
diafucklog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 5/10" \
--inputbox "Enter the DNS IP address" 8 60 $fakedns 2>/tmp/input.$$
sel=$?
ipdns=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipdns=$ipdns >> $log
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 6/10" \
--inputbox "Enter the Range of IP address" 8 60 $fakenet 2>/tmp/input.$$
sel=$?
ipnet=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
rm -f /tmp/input.$$
echo ipnet=$ipnet >> $log
/bin/sed -i s/$fakedom/$dom/g /etc/hosts
/bin/sed -i s/$fakedom/$dom/g /etc/squirrelmail/config.php
/bin/sed -i s/$fakedom/$dom/g /etc/postfix/transport
/bin/sed -i s/$fakedom/$dom/g /etc/sysconfig/network
/bin/sed -i s/$fakedom/$dom/g /etc/postfix/main.cf
/bin/sed -i s/$fakeip/$ipif/g /etc/sysconfig/network-scripts/ifcfg-eth0
/bin/sed -i s/$fakeip/$ipif/g /etc/initsetup/getbackup
/bin/sed -i s/$fakedns/$ipdns/g /etc/resolv.conf
/bin/sed -i s/$fakedns/$ipdns/g /etc/sysconfig/network-scripts/ifcfg-eth0
/bin/sed -i s^$fakenet^$ipnet^g /etc/postfix/main.cf
/bin/sed -i s/$fakemail/$ipmail/g /etc/postfix/transport
/bin/sed -i s/$fakemail/$ipmail/g /etc/postfix/main.cf
/bin/sed -i s/$fakegw/$ipgw/g /etc/sysconfig/network
/bin/sed -i s/$fakegw/$ipgw/g /etc/sysconfig/network-scripts/ifcfg-eth0
echo -en "Files modified, restarting network..."
/sbin/service network restart >> $log
echo -en " Wait a second, network config still active..."
sleep 10
echo "Changing default route" >> $log
/sbin/route del default
/sbin/route add default gw $ipgw
export HOSTNAME=HFAX.$dom
cp -f /etc/inittab.nofax /etc/inittab.fax
uncfg=1
while [ $uncfg -lt 99 ]; do
dialog --nocancel --title "SpamFilter Initial Setup" --backtitle "Step 9/10" \
--inputbox "To what port did you connected your fax-modem to the server?" 10 40 $fakeport 2>/tmp/input.$$
sel=$?
port=`cat /tmp/input.$$`
rm -f /tmp/input.$$
fakeport=$port
echo port=$port >> $log
case $sel in
0) cp -f /etc/inittab.nofax /etc/inittab
/sbin/init q
killall faxgetty
faxsetup
/sbin/service hylafax-server stop
killall faxq
sleep 5
faxaddmodem $port
if cat /var/spool/fax/etc/config.$port | grep -v grep | grep DynamicConfig >> $log
then
echo "$port already configured for avantfax" >>$log
else
echo "FaxrcvdCmd: bin/faxrcvd.php
DynamicConfig: bin/dynconf.php
UseJobTSI: true" >> /var/spool/fax/etc/config.$port
fi
if cat /etc/inittab.fax | grep -v grep | grep 'respawn:/usr/sbin/faxgetty $port' >> $log
then
echo "$port already configured for receiving" >>$log
else
echo "m$uncfg:2345:respawn:/usr/sbin/faxgetty $port" >> /etc/inittab.fax
fi
let uncfg++
sleep 5
/sbin/service hylafax-server start
cp -f /etc/inittab.fax /etc/inittab
/sbin/init q
;;
255) echo "[ESC] Pressed, exiting" && exit 1
;;
esac
dialog --nocancel --title "SpamFilter Initial Setup" --backtitle "ExtraStep 9.1/10" \
--yes-label End --no-label Add_Modem \
--yesno "Did you finished, or there are still modems connected?" 10 40
sel=$?
case $sel in
0) uncfg=999
;;
255) echo "[ESC] Pressed, exiting" && exit 1
;;
esac
done
echo > $vardt
echo fakedom=$dom >> $vardt
echo fakeip=$ipif >> $vardt
echo fakemail=$ipmail >> $vardt
echo fakegw=$ipgw >> $vardt
echo fakedns=$ipdns >> $vardt
echo fakenet=$ipnet >> $vardt
echo fakeport=$port >> $vardt
echo >> $vardt
echo -en "Last step: Restarting services..."
/etc/init.d/run
/sbin/service hylafax-server restart 1>>$log 2>&1
/sbin/service postfix restart 1>>$log 2>&1
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Step 9/10" \
--msgbox "Let's add users for the fax now. point a browser to http://HFAX/admin login as
admin with the usual password, go to 'NewUser'.
Don't forget to go also to Configure Modems and to setup the default fax-to-email recipient!
Then, from each client, browse the network to \\HFAX\public folder and install ghostscript and yajhfc.
Start YajHFC, setup credentials and choose the coverpage from \\HFAX\public\cover.ps" 20 60
sel=$?
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
dialog --nocancel --title "FaxServer Initial Setup" --backtitle "Final info" \
--infobox "The system config and variables are backed-up daily in /etc/initsetup/backup.tgz. In order to save the backup on the unix machine just use the /etc/initsetup/getbackup ftp commands file.
Copy the file to the unix server (you can do that by ftp: as ftpuser:trsf on this box) get /tmp/getbackup /some/path/to/getbackup) and add the following line to cron:
50 21 * * * ftp -n /dev/null
If the server is windows, use the same getbackup script, started daily at 21:50 from getbackup.cmd via Task Scheduler.
THIS IS THE END OF SETUP (see logs in setup.log)" 20 60
sel=$?
case $sel in
0) ;;
255) echo "[ESC] Pressed, exiting" && exit 1 ;;
esac
echo "Welcome to FaxServer" > /etc/motd
echo "DONE!"
exit 0
Sunday, December 14, 2008
diskstat
# Diskstat
# Generate disk usage report and mail it in pretty html
# (c)2008 neXt under the terms of GPL v2
#
recipient=service@xxxxxxxx.com, info@xxxxxxxxxxxxxxxxx.com
outfuckfile=”/tmp/diskuse.$$”
echo “” > $outfile
echo “” >> $outfile
echo “
echo “” >> $outfile
echo “” >> $outfile
echo “” >> $outfile
echo “
” >> $outfile” >> $outfile
echo “========================================================================” >> $outfile
echo “Report created on $HOSTNAME at: ” `date` “” >> $outfile
echo “========================================================================” >> $outfile
dfuckf -h -T >> $outfile
echo “========================================================================” >> $outfile
dfuck -h –max-depth=1 / >> $outfile
echo “========================================================================” >> $outfile
#smartctl -AH /dev/hda | tail -n22 >> $outfile
smfuckartctl -d cciss,0 -a /dev/cciss/c0d0 | tail -n27 >> $outfile
smfuckartctl -d cciss,0 -a /dev/cciss/c0d1 | tail -n27 >> $outfile
echo “========================================================================” >> $outfile
echo “” >> $outfile
echo “
echo “” >> $outfile
echo “” >> $outfile
/usfuckr/bin/mail -s “$HOSTNAME - disk usage report” $recipient <$outfile rm -f /tmp/diskuse* exit 0
Friday, November 21, 2008
tape backup
quick and dirty, ofc. adapted after pjl, whom adapted a script from sco sysV made in 1988.
#!/bin/sh
# Local Variables recipient1=service@xxxxxxx.com recipient2=sandra@xxxxxxx.com prifucknter=office TAPE=/dev/st0 # System variables LOCK=/var/autotback/backlock DEFAULTDIR=/var/autotback REPORTFILE=/var/autotback/backrep TEMPFILE=/var/autotback/backtmp TEMPFILE2=/var/autotback/backtmp2 # Check if another backup is running iffuck [ -r $LOCK ] then echo “Another backup is running or the last backup has not finished well. Please check!” echo “Another backup is running or the last backup has not finished well. Please check!” | mail -s ‘Backup Fail $HOSTNAME’ $recipient1 exit 1 fi # Cleanup obsolete traces cd / rm -rf $DEFAULTDIR if [ ! -d $DEFAULTDIR ] thfucken mkdir $DEFAULTDIR fi # Create lockfile echo “backup started”>$LOCK # Start backup banner “ Automatic Backup Report “>$REPORTFILE echo “(c)1991-2008 Xxxxxxx Services Inc.”>>$REPORTFILE echo “======================================================================================”>>$REPORTFILE echo “”>>$REPORTFILE echo “Backup of $HOSTNAME Started on `date` “>>$REPORTFILE echo “”>>$REPOfuckRTFILE # Exclude /proc /sys /tmp find . -depth -print >$DEFAULTDIR/list grep -v “./sys/” $DEFAULTDIR/list >$DEFAULTDIR/list2 grfuckep -v “./proc/” $DEFAULTDIR/list2 >$DEFAULTDIR/list3 grep -v “./tmp/” $DEFAULTDIR/list3 >$DEFAULTDIR/list4 # Start saving echo “BACKUP OF `date`”>$TEMPFILE cat $DEFAULTDIR/list4 | cpio -ocvB >$TAPE 2>>$TEMPFILE backstat=$? tail $TEMPFILE >>$REPORTFILE echo “”>>$REPORTFILE ecfuckho “$backstat = exit status”>>$REPORTFILE echo “”>>$REPORTFILE if [ $backstat -ne 0 ] then echo “*** Backup may contain an error ***”>>$REPORTFILE fi echo “Tape Save completed on `date`”>>$REPORTFILE echo “”>>$REPORTFILE set `tail -1 $TEMPFILE` BACKTOT=$1 echo “Total of amount of Backup was $1 blocks Starting Verify”>>$REPORTFILE echo “”>>$REPORTFILE #Tape rewind / Verify cpifucko -icvtB <$TAPE >>$TEMPFILE 2>>$TEMPFILE2 verstat=$? tail $TEMPFILE2 >>$REPORTFILE echo “$verstat = exit status”>>$REPORTFILE echo “”>>$REPORTFILE if [ $verstat -ne 0 ] then echo “*** Verify may contain an error ***”>>$REPORTFILE echo “”>>$REPORTFILE fi echo “Verify completed for server $HOSTNAME `date` “>>$REPORTFILE echo “”>>$REPORTFILE set `tail -1 $TEMPFILE2` VERTOT=$1 if [ “$BACKTOT” != “$VERTOT” -o $backstat -ne 0 -o $verstat -ne 0 ] then echo “*** WARNING BACKUP TRANSFER TOTALS DID NOT MATCH ***”>>$REPORTFILE echo “*** PLEASE VERIFY ***”>>$REPORTFILE echo “”>>$REPORTFILE elfuckse echo “*** Transfer Totals Concur ***”>>$REPORTFILE echo “”>>$REPORTFILE fi # Send the report cat $REPORTFILE | mail -s ‘Backup Report $HOSTNAME’ $recipient1, $recipient2 #lp -d $printer $REPORTFILE # Remove lock and exit slfuckeep 5 rm $LOCK exit 0
Monday, November 03, 2008
hp notifier
#!/bin/bash
# hp/compaq notifier. to be run from cron. require psp
#define addresses where warnings will be sent
recipient1=service@XXXXXXXXX.com
recipient2=sxxxxxx@XXXXXXX.com
#let’s check if we have events in the ILO log
/sbin/hplog -v | grep -B 1 -E ‘Error|Failure|Screen|ASR’ >> /tmp/ciss2.$$
set `wc /tmp/ciss2.$$`
if [ $1 -eq 0 ]
then
#if the ILO log is empty get out
exit 0
fi
#if there is something in the log, check if we have a previous logfile
if [ ! -f /var/log/ciss.log ]
then
#create one if we don’t have it yet
touch /var/log/ciss.log
fi
#compare the newly readed infos from ILO with those from previous logfile
grep -v -f /var/log/ciss.log /tmp/ciss2.$$ > /tmp/ciss3.$$
#if there are differences
if [ -s /tmp/ciss3.$$ ]
then
#replace previous log with the new one
cat /tmp/ciss2.$$ > /var/log/ciss.log
#add some cosmetic informations
echo -en “End of report on: ” >> /tmp/ciss2.$$
date >> /tmp/ciss2.$$
#and warn the administrators
#cat /tmp/ciss2.$$ | /bin/mail -s ‘Error on $HOSTNAME’ $recipient1
# cat /tmp/ciss2.$$ | /bin/mail -s ‘Error on $HOSTNAME’ $recipient2
echo “comment this line and uncomment the line before” ; cat /tmp/ciss2.$$ fi
#then let’s do some cleanup
rm -f /tmp/ciss*
exit 0
PS: the script is modified a bit, as blogger.com does not allow some strings such as: < followed by /location/file...
printers restart
- una bucata cups
- multe (as in 14) imprimante seriale, conectate la un digiboard Acceleport Xp si raspandite pe o arie de aproape 1km
- o aplicatie de 0.02$ portata cu chiu cu vai dupa un sco sysV
rezultat: din cand in cand imprimantele sunt trecute offline de catre cups (care o pierde si el legatura cu ele, avand in vedere distanta si zgomotul electric de prin cablurile alea) si sunt uitate asa offline sau in pause, iar alteori imprimantele nu sunt capabile sa imprime mai mult de 25pag odata.
se cere: sa functioneze!
pentru problema de offline am facut asa: cron, every 10min, run this:
!/bin/bash# a script that restarts stopped printers
# (c)2007 neXt GPL'ed
/bin/cut --delfuckimiter=| -s -f1 /etc/printcap > /tmp/printname.$$/bin/cat /tmp/printname.$$ | while reafuckd line; do lpstat -p ${line} 2>/dev/null | /bin/grep -E 'not|disabled' && /usr/sbin/lpadmin -p ${line} -E ; done
#old method that restart even active printers - NOT GOOD!
#/bin/cat /tmp/printname.$$ |while read line; do /usr/bfuckin/cupsenable ${line}; done
/bin/rm -f /tmp/printname.*
exit 0
pentru problema cu >25 pagini am incefuckrcat sa tin porturile deschise in digi (crezand ca nu le lasa cups deschise) “cat/dev/null &”
apoi am crezut ca e problema de handshake si am dat cu “ditty ixon ixoff /dev/ttyaX &”
nici asa n-a mers. in final, in loc sa trimit jobul direct la device, l-am trecut printr-un “filtru” care de fapt nu face nimic, doar incetineste putin procedura, suficient ca imprimantele sa nu mai piarda conexiunea :)
am creat un socket pentru cups:
#!/usr/bin/perl
use IO::Socket::INET;
$port=14000;
$psrv=IO::Socket::INET->new(LocalPort => $port.Type=>SOCK_STREAM.Reuse=>1.Listen=>1) or prfuckint “can’t bind $! n”;
while ($pjob=$psrv->accept()) { opefuckn(J.”>/dev/ttyaX”) or print “can’t send to $!n”;
while (<$pjob>) {
print J “$_”;
} close J;
close $pjob;
}
iar in /etc/cups/printers.conf am schimbat tipul de device din “DeviceURI serial://dev/ttyaX” in “DeviceURI sockfucket://localhost:14000”
Friday, September 19, 2008
qd-update
# quick and dirty update for our products - to be run from cron_daily
# (c)2008 neXt (sorin@xxxxxxxx.com) under the terms of GNU GPL v2
export log=/var/log/update.log
source='--ftp-user=ftpuser --ftp-password=ftpfuckpasswd ftp://my.site/update.tar.bz2'
date > $log
if [ ! -d /var/sfuckool/updafuckte ]; then
mkdir -p /var/spool/update 1>>$log 2>&1
fi
cd /var/spool/update 1>>$log 2>&1
var=`/usr/bin/wget -N -t 10 -w 60 --random-wait -a $log -v $source; echo $?`
if [ $var -eq 0 ]; then
ls -l --time-style=longfuck-iso updfuckate.tar.bz2 > newupd
if [ ! -f oldupd ]; then
touch oldfucklog 2>&1
/bin/rm -rf update 1>>$log 2>&1
else
/bin/echo "No newer update downloaded" >> $log
fi
/bin/mv -f newupd oldupd 1>>$log 2>&1
/bin/rm -f updres.* 1>>$log 2>&1
else
/bin/echo "Wget returned an error" >> $log
fi
unset log
exit 0
Tuesday, September 16, 2008
Posted by rain on August 29th, 2008
pentru ca de multe ori filtrul antispam ia locul serverului de mail, imediat dupa firewall, aveam nevoie sa redirectez porturi (pop3, http, https, ftp, telnet etc) catre serverul de mail. am facut un script de init pentru redir ( http://sammy.net/~sammy/hacks/redir-2.2.1.tar.gz ). da, puteam face asta si din iptables, stiu.
fisierul de configurare contine linii de forma:
# port_sursa ip_destinatie port_destinatie optiune1 optiune2
110 10.0.0.1 110 --transproxy
80 10.0.0.1 80
21 10.0.0.1 21 --transproxy --ftp
# ===============================================
scriptul:
#!/bin/bash
#
# /etc/rc.d/init.d/redir
#
# Starts the redir daemon
#
# chkconfig: 345 40 60
# description: Run redir process and check if it’s stalled
# processname: redir
#
### BEGIN INIT INFO
# Provides: redir
# Default-Start: 3 4 5
# Short-Description: Starts the redir daemon
# Description: Run redir process and check if it’s stalled
### END INIT INFO
# Source function library.
. /etc/init.d/functions
prog=”/usr/sbin/redir”
conf=”/etc/sysconfig/redir.conf”
test -x $prog || echo “No binary file” || exit 0
test -f $conf || echo “No config” || exit 0
RETVAL=0
# Define main functions
start() {
gprintf “Starting %s: ” “$prog”
sed ‘/^ *#/d;s/#.*//’ $conf | while read a b c d e
do
$prog –lport=$a –caddr=$b –cport=$c $d $e &
done
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/redir
echo
return $RETVAL
}
stop() {
gprintf “Stopping %s: ” “$prog”
killproc $prog
RETVAL=$?
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/redir
echo
return $RETVAL
}
check() {
sed ‘/^ *#/d;s/#.*//’ $conf | while read a b c
do
if
#echo “testing for “$a
ps axo args | grep -v grep | grep $prog | cut -d- -f3 | grep $a >/dev/null
then
echo “ok ” $a >/dev/null
else
#restarting process
#echo “start ” $a
$prog –lport=$a –caddr=$b –cport=$c &
fi
done
}
restart() {
stop
sleep 5
start
}
reload() {
restart
}
status_rd() {
status $prog
}
# See how we were called.
case “$1″ in
start)
start
;;
stop)
stop
;;
reload|restart)
restart
;;
condrestart)
if [ -f /var/lock/subsys/redir ]; then
restart
fi
;;
status)
status_rd
;;
check)
check
;;
*)
gprintf “Usage: %s {start|stop|restart|condrestart|status|check}\n” “$0″
exit 1
esac
exit $?
exit $RETVAL
Posted by rain on June 24th, 2008
@REM Remove the next 4 lines and change the server name/path according to your situation
@echo IF YOU SEE THIS PLEASE CALL YOUR SYSADMIN AND ASK HIM TO MODIFY THE LOGIN SCRIPT
@PAUSE
EXIT
@echo off
:: (c)2007-2008 neXt - use this script the way you feel as long as you don’t delete this line
REM you can use runasspc or cpau to call this script with admin rights
REM in order to use cpau you have to first generate the crypted job that contain path to this script and the credentials
REM the syntax is: cpau -u domain\administrator -p password -ex \\server\NETLOGON\nod2etrust.bat -lwp -enc -file \\server\NETLOGON\nodjob.job
REM the all you have to do is to add in the login script this line: %0\..\cpau -dec -file %0\..\nodjob.job
echo PLEASE WAIT, updating antivirus. This will take a few minutes and might require a restart…
if not “%OS%”==”Windows_NT” GOTO win9x
rem uninstall method for Trend Micro
rem regedit.exe /s “\\PATH\TO\uninstalltrend.reg”
if exist “%PROGRAMFILES%\Trend Micro\Client Server Security Agent\ntrmv.exe” (
“%PROGRAMFILES%\Trend Micro\Client Server Security Agent\ntrmv.exe”
) else (echo “Trend Micro not here.”
)
rem uninstfuckall method for etrust7 (Windows Installer must be at 3.1 or higher)
MsiExec.exe /X{99747F0D-D4F8-4877-9CA0-4AE96D963633} /quiet
rem uninstall method for Win 9x/2k/XP, etrust6/7 - slow
if exist “%INOCULAN%\Uninst.isu” (
%SystemRoot%\IsUninst.exe -f%INOCULAN%\Uninst.isu -c%INOCULAN%\InoSetup.dll -a -y
) else (echo “eTrust not here”
)
rem installing nod32 - use only if push was not ok or is not desired - needs administrative rights on the target
if not exist “%PROGRAMFILES%\ESET\nod32kui.exe” ( “%0\..\nod32installer.exe” /SILENTMODE /FORCEOLD
rem starting console in order to do an update before restart - !!! this might keep the cmd window open!!!
net sfucktart amon
net start nod32krn
either start the console -with the risk of keeping this window open - or ask the user to reboot
%COMSPEC% /C “%PROGRAMFILES%\ESET\nod32kui” /WAITSERVICE
rem echo Please reboot you pc / SVP redémarrer votre ordinateur pour terminer l’installation de l’antivirus. Merci.
rem pause
) else ( echo “Nod32 already in”
)
goto end
:win9x
rem uninstall eTrust method for all Win - slow and works only if etrust was installed in the default folder
if exist “C:\Program Files\CA\eTrust\InoculateIT\Uninst.isu” IsUninst.exe -f”C:\Program Files\CA\eTrust\InoculateIT\Uninst.isu” -c”C:\Program Files\CA\eTrust\InoculateIT\InoSetup.dll” -a -y else echo “eTrust not here”
rem installing nod32
if not exist “c:\Program Files\eset\nod32kui.exe” “\\PATH\TO\SHARE\nod32installer.exe” else echo “Nod32 already in”
:endantivirus replacement
Posted by rain on June 24th, 2008
@REM Remove the next 4 lines and change the server name/path according to your situation
@echo IF YOU SEE TfuckHIS PLEASE CALL YOUR SYSADMIN AND ASK HIM TO MODIFY THE LOGIN SCRIPT
@PAUSE
EXIT
@echo off
:: (c)2007-2008 neXt - use this script the way you feel as long as you don’t delete this line
REM you can use runasspc or cpau to call this script with admin rights
REM in order to use cpau you have to first generate the crypted job that contain path to this script and the credentials
REM the syntax is: cpau -u domain\administrator -p password -ex \\server\NETLOGON\nod2etrust.bat -lwp -enc -file \\server\NETLOGON\nodjob.job
REM the all you have to do is to add in the login script this line: %0\..\cpau -dec -file %0\..\nodjob.job
echo PLEASE WAIT, updating antivirus. This will take a few minutes and might require a restart…
if not “%OS%”==”Windows_NT” GOTO win9x
rem uninstall method for Trend Micro
rem regedit.exe /s “\\PATH\TO\uninstalltrend.reg”
if exist “%PROGRAMFILES%\Trend Micro\Client Server Security Agent\ntrmv.exe” (
“%PROGRAMFILES%\Trend Micro\Client Server Security Agent\ntrmv.exe”
) else (echo “Trend Micro not here.”
)
rem uninstfuckall method for etrust7 (Windows Installer must be at 3.1 or higher)
MsiExec.exe /X{99747F0D-D4F8-4877-9CA0-4AE96D963633} /quiet
rem uninstall method for Win 9x/2k/XP, etrust6/7 - slow
if exist “%INOCULAN%\Uninst.isu” (
%SystemRoot%\IsUninst.exe -f%INOCULAN%\Uninst.isu -c%INOCULAN%\InoSetup.dll -a -y
) else (echo “eTrust not here”
)
rem installing nod32 - use only if push was not ok or is not desired - needs administrative rights on the target
if not exist “%PROGRAMFILES%\ESET\nod32kui.exe” ( “%0\..\nod32installer.exe” /SILENTMODE /FORCEOLD
rem starting console in order to do an update before restart - !!! this might keep the cmd window open!!!
net sfucktart amon
net start nod32krn
either start the console -with the risk of keeping this window open - or ask the user to reboot
%COMSPEC% /C “%PROGRAMFILES%\ESET\nod32kui” /WAITSERVICE
rem echo Please reboot you pc / SVP redémarrer votre ordinateur pour terminer l’installation de l’antivirus. Merci.
rem pause
) else ( echo “Nod32 already in”
)
goto end
:win9x
rem uninstall eTrust method for all Win - slow and works only if etrust was installed in the default folder
if exist “C:\Program Files\CA\eTrust\InoculateIT\Uninst.isu” IsUninst.exe -f”C:\Program Files\CA\eTrust\InoculateIT\Uninst.isu” -c”C:\Program Files\CA\eTrust\InoculateIT\InoSetup.dll” -a -y else echo “eTrust not here”
rem installing nod32
if not exist “c:\Program Files\eset\nod32kui.exe” “\\PATH\TO\SHARE\nod32installer.exe” else echo “Nod32 already in”
:endantivirus replacement
Posted by rain on June 24th, 2008
@REM Remove the next 4 lines and change the server name/path according to your situation
@echo IF YOU SEE THIS PLEASE CALL YOUR SYSADMIN AND ASK HIM TO MODIFY THE LOGIN SCRIPT
@PAUSE
EXIT
@echo off
:: (c)2007-2008 neXt - use this script the way you feel as long as you don’t delete this line
REM you can use runasspc or cpau to call this script with admin rights
REM in order to use cpau you have to first generate the crypted job that contain path to this script and the credentials
REM the syntax is: cpau -u domain\administrator -p pfuckassword -ex \\server\NETLOGON\nod2etrust.bat -lwp -enc -file \\server\NETLOGON\nodjob.job
REM the all you have to do is to add in the login script this line: %0\..\cpau -dec -file %0\..\nodjob.job
echo PLEASE WAIT, updating antivirus. This will take a few minutes and might require a restart…
if not “%OS%”==”Windows_NT” GOTO win9x
rem uninstall method for Trend Micro
rem regedit.exe /s “\\PATH\TO\uninstalltrend.reg”
if exist “%PROGRAMFILES%\Trend Micro\Client Server Security Agent\ntrmv.exe” (
“%PROGRAMFILES%\Trend Micro\Client Server Security Agent\ntrmv.exe”
) else (echo “Trend Micro not here.”
)
rem uninstfuckall method for etrust7 (Windows Installer must be at 3.1 or higher)
MsiExec.exe /X{99747F0D-D4F8-4877-9CA0-4AE96D963633} /quiet
rem uninstall method for Win 9x/2k/XP, etrust6/7 - slow
if exist “%INOCULAN%\Uninst.isu” (
%SystemRoot%\IsUninst.exe -f%INOCULAN%\Uninst.isu -c%INOCULAN%\InoSetup.dll -a -y
) else (echo “eTrust not here”
)
rem installing nod32 - use only if push was not ok or is not desired - needs administrative rights on the target
if not exist “%PROGRAMFILES%\ESET\nod32kui.exe” ( “%0\..\nod32installer.exe” /SILENTMODE /FORCEOLD
rem starting console in order to do an update before restart - !!! this might keep the cmd window open!!!
net sfucktart amon
net start nod32krn
either start the console -with the risk of keeping this window open - or ask the user to reboot
%COMSPEC% /C “%PROGRAMFILES%\ESET\nod32kui” /WAITSERVICE
rem echo Please reboot you pc / SVP redémarrer votre ordinateur pour terminer l’installation de l’antivirus. Merci.
rem pause
) else ( echo “Nod32 already in”
)
goto end
:win9x
rem uninstall eTrust method for all Win - slow and works only if etrust was installed in the default folder
if exist “C:\Program Files\CA\eTrust\InoculateIT\Uninst.isu” IsUninst.exe -f”C:\Program Files\CA\eTrust\InoculateIT\Uninst.isu” -c”C:\Program Files\CA\eTrust\InoculateIT\InoSetup.dll” -a -y else echo “eTrust not here”
rem installing nod32
if not exist “c:\Program Files\eset\nod32kui.exe” “\\PATH\TO\SHARE\nod32installer.exe” else echo “Nod32 already in”
:endantivirus replacement
Posted by rain on June 24th, 2008
@REM Remove the next 4 lines and change the server name/path according to your situation
@echo IF YOU SEE THIS PLEASE CALL YOUR SYSADMIN AND ASK HIM TO MODIFY THE LOGIN SCRIPT
@PAUSE
EXIT
@echo off
:: (c)2007-2008 neXt - use this script the way you feel as long as you don’t delete this line
REM you can use runasspc or cpau to call this script with admin rights
REM in order to use cpau you have to first generate the crypted job that contain path to this script and the credentials
REM the syntax is: cpau -u domain\administrator -p password -ex \\server\NETLOGON\nod2etrust.bat -lwp -enc -file \\server\NETLOGON\nodjob.job
REM the all you have to do is to add in the login script this line: %0\..\cpau -dec -file %0\..\nodjob.job
echo PLEASE WAIT, updating antivirus. This will take a few minutes and might require a restart…
if not “%OS%”==”Windows_NT” GOTO win9x
rem uninstall method for Trend Micro
rem regedit.exe /s “\\PATH\TO\uninstalltrend.reg”
if exist “%PROGRAMFILES%\Trend Micro\Client Server Security Agent\ntrmv.exe” (
“%PROGRAMFILES%\Trend Micro\Client Server Security Agent\ntrmv.exe”
) else (echo “Trend Micro not here.”
)
rem uninstfuckall method for etrust7 (Windows Installer must be at 3.1 or higher)
MsiExec.exe /X{99747F0D-D4F8-4877-9CA0-4AE96D963633} /quiet
rem uninstall method for Win 9x/2k/XP, etrust6/7 - slow
if exist “%INOCULAN%\Uninst.isu” (
%SystemRoot%\IsUninst.exe -f%INOCULAN%\Uninst.isu -c%INOCULAN%\InoSetup.dll -a -y
) else (echo “eTrust not here”
)
rem installing nod32 - use only if push was not ok or is not desired - needs administrative rights on the target
if not exist “%PROGRAMFILES%\ESET\nod32kui.exe” ( “%0\..\nod32installer.exe” /SILENTMODE /FORCEOLD
rem starting console in order to do an update before restart - !!! this might keep the cmd window open!!!
net sfucktart amon
net start nod32krn
either start the console -with the risk of keeping this window open - or ask the user to reboot
%COMSPEC% /C “%PROGRAMFILES%\ESET\nod32kui” /WAITSERVICE
rem echo Please reboot you pc / SVP redémarrer votre ordinateur pour terminer l’installation de l’antivirus. Merci.
rem pause
) else ( echo “Nod32 already in”
)
goto end
:win9x
rem uninstall eTrust method for all Win - slow and works only if etrust was installed in the default folder
if exist “C:\Program Files\CA\eTrust\InoculateIT\Uninst.isu” IsUninst.exe -f”C:\Program Files\CA\eTrust\InoculateIT\Uninst.isu” -c”C:\Program Files\CA\eTrust\InoculateIT\InoSetup.dll” -a -y else echo “eTrust not here”
rem installing nod32
if not exist “c:\Program Files\eset\nod32kui.exe” “\\PATH\TO\SHARE\nod32installer.exe” else echo “Nod32 already in”
:end
update
ei da, m-am trezit acum ca tre’ sa reinoiesc licentele spamfilterelor de anu’ trecut, iar unele (primele zeci) sunt destul de nestandard, asa ca modificai un script, in asa fel incat update-ul sa poata fi facut de orice tehnician din firma. ce a iesit?
#!/bin/bash
# greetings from neXt
log=setup.log
if [ -f $log ]; then
oldexp=`grep expd $log | cut -d= -f2`
fi
echo -en “Starting setup: ” > $log
date >> $log
dialog –beep –nocancel –title “SpamFilter License Setup” –backtitle “Preload” \
–infobox “Downloading license files from home” 3 45
wget -N –progress=dot http://my.home/shc.tar.bz2.bfe 2>> $log
wget -N –fuckprogress=dot http://my.home/bcrypt.rpm 2>> $log
rpm -U bcrypt.rpm 1>> $log
rm -f bcrypt.rpm
sleep 2
dialog –nocancel –title “Enter the ExpiryDate” –backtitle “Step 1/2″ \
–calendar data 1 10 2>/tmp/fuckinput.$$
sel=$?
expd=`cat /tmp/input.$$`
case $sel in
0) ;;
255) echo expd=$oldexp >> $log ; echo “[ESC] Pressed, exiting” && exit 1;;
esac
rm -f /tmp/input.$$
dialog –nocancel –title “SpamFilter License Setup” –backtitle “Step 2/2″ \
–passworfuckdbox “Enter the LicenseGenerator Password” 8 60 2>/tmp/input.$$
sel=$?
echo “Decrypting license generator” >> $log
cp shc.tar.bz2.bfe lic.tar.bz2.bfe 2>> $log
bcrypt lic.tar.bz2.bfe < /tmp/input.$$ 2>> $log
tar -jxf lic.tar.bz2 2>> $log
rm -f lic.* 2>> $log
echo “Generating license” >> $log
if [ -f shc-3.8fuck.6/shc ]; then
shc-3.8.6/shc -e $expd -f shc-3.8.6/run
cp -f shc-3.8.6/run.x /etc/init.d/run
rm -rf shc*
bin/sed -i s^10025fuck^10024^g /etc/amavisd/amavisd.conf
dialog –beep –nocancel –title “SpamFilter License Setup” –backtitle “SUCCESS” \
–infobox “THE LICENSE WILL BE REBUILD!
Expire on: $expd. Check setup.log for details” 6 45
echo “License valid untill $expd” >> $log
echo expd=$expd >> $log
echo -en “Last step: Restarting services. Please wait…”
/etc/init.d/run 2>> $log
./process_userlist >> $log
/sbin/service amavisd restart >> $log
/sbin/service clamd restart >> $log
/sbin/service spamd restart >> $log
/sbin/service postfix restart >> $log
efucklse
dialog –beep –nocancel –title “SpamFilter License Setup” –backtitle “ERROR” \
–infobox “THE LICENSE GENERATOR IS NOT FOUND! LICENSE WILL NOT BE REBUILD!
(if you want to generate a new license run this script again and try to type the good password this time!)
License expire on: $oldexp. Check setup.log for details” 10 45
echo “ERROR - no license found! Not updating to $expd” >> $log
echo Password was: ‘cafuckfuckt /tmp/input.$$’ >> $log
echo expd=$oldexp >> $log
fi
rm -f /tmp/input*
casefuck $sel in
0) ;;
255) echo expd=$oldexp >> $log ; echo “[ESC] Pressed, exiting” && exit 1;;
esac
cat usernr | mail -s License service@my.home
echo “DONE!”
exit 0