Modify Perl script to work with txt - Permissions script


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Modify Perl script to work with txt - Permissions script
# 1  
Old 09-12-2007
Bug Modify Perl script to work with txt - Permissions script

Hi

I have this code, and i want work with a ls -shalR output in .txt

What i need read to do this??

Where start?


Code:
#!/usr/bin/perl

# Allrights- A perl tool for making backups of file permissions

# Copyright (C) 2005 Norbert Klein <norbert@acodedb.com>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

# Version 1.02


# Change log

# From 1.01 to 1.02
# -----------------
# 2005-12-18 
# Fixed: File names with only one character are ignored

# From 1.0 to 1.01
# ---------------- 
# 2005-12-16 
# Many thanks to Marc Mims who found and fixed 3 bugs:
# Fixed: No support for file names with single quotes
# Fixed: Misinterpretation of file names starting with dashes
# Fixed: Restore crashes if executed on non-existing directories   



use strict;
use warnings;
use diagnostics;
use Cwd;
use File::Spec::Functions;


my $error="";
my $startdir="";

if ($ARGV[0]){
  #help text if argument is passed to script
  if ($ARGV[0] =~ /^(\?|help|-h|--help)$/) {
print <<'END';
  
  This script allows you to backup and restore file properties. It backups the 
  permissions, owners and groups of all files and folders including all subfolders. 
  IT DOES NOT BACKUP THE FILES AND FOLDERS THEMSELVES !!!

  Usage: ./allrights.pl  [DIR | OPTION]

  Examples: ./allrights.pl
            ./allrights.pl --help
            ./allrights.pl /folder1/folder2
            ./allrights.pl ./folder2

  DIR: 
  Directory were to start the backup (starting point of recursive descend)
  
  OPTIONS: 
  ?, help, -help, --help will display this help text
  
  Without parameter the starting point for the backup will be the current working directory	
	
	
  BACKUP
  ------
  Run the script including the path to the directory you want to backup or run it inside this
  directory without paramters. Two executable files will be created within this folder:
  
  permissions_backup.sh
  ownergroup_backup.sh
 
  Both are simple shell scripts which do not need Perl and can be run independently. 
  The program backups hidden files and hidden folders also. But note that symbolic links 
  will be ignored. If a symbolic link points to a file outside of the saved directory tree, 
  this file will remain unchanged too. 
  If a user name or group name does not exist any more in /etc/passwd or /etc/group the uid or 
  gid itself will be written into the backup files instead of the names. This happens if
  a group or user has been deleted, but files with these ids still exist.
    
	
  RESTORE
  -------
  You can run the two backup scripts independently. If you want to restore permissions 
  and owner/group just run both. In case you have removed some files since the last 
  backup, the script output will show you which files couldn't be found. 
  
  
  Author: norbert@acodedb.com
  Have fun !
  
END
  exit();
  }else{
    #if user passes relative path, change to absolute path
    if (substr($ARGV[0],0,1) eq "/"){
      $startdir=$ARGV[0];
    }else{
      $startdir=cwd() . "/" . $ARGV[0];
      $startdir =~ s|^//|/|;
    }   
  }  
}else{
  $startdir=cwd();
}

#first line in every output shall be empty
printf "\n";

#check if folder passed by user exists
if (!-e $startdir) {
  $error=" The folder $startdir does not exist";
  &finish();
}


#get content from /etc/passwd and /etc/group for uid/gid -> username/groupname translation
my %unames=();
my %gnames=();

#the script will produce a correct backup, also if etc/passwd cannot be opened
if (!open(FILE,"/etc/passwd")){
  $error=" The file \"/etc/passwd\" could not be opened\n";
  $error.=" This means that your backup scripts (.sh) have been created with UIDs instead of names (just a matter of clearness)\n";
  $error.=" Your backup has been created successfully\n";
  $error.=" You can restore your permissions and owners/groups by running \"./permissions_backup.sh\" and/or \"./ownergroup_backup.sh\"";
}else {
  my $uname="";
  my $uid="";
  while (<FILE>) {
    #skip comments
    if($_=~/^\s*#/){ next; }
    my @l=split(":",$_);
    $uname=$l[0];
    $uid=$l[2];
    $unames{$uid}=$uname;
  }
}
close(FILE);

#the script will produce a correct backup, also if /etc/group cannot be opened
if (!open(FILE,"/etc/group")){
  $error=" The file \"/etc/group\" could not be opened\n";
  $error.=" This means that your backup scripts (.sh) have been created with GIDs instead of names (just a matter of clearness)\n";
  $error.=" Your backup has been created successfully\n";
  $error.=" You can restore your permissions and owners/groups by running \"./permissions_backup.sh\" and/or \"./ownergroup_backup.sh\"";
}else {
  my $gname="";
  my $gid="";
  while (<FILE>) {
    #skip comments
    if($_=~/^\s*#/){ next; } 
    my @l=split(":",$_);
    $gname=$l[0];
    $gid=$l[2];
    $gnames{$gid}=$gname;
  }
} 
close(FILE);


#check if backupfiles already exists
if (-e "permissions_backup.sh"){
  $error= " The backup file \"permissions_backup.sh\" already exists\n";
  $error.=" Please rename or remove it as previous backup files will not be overwritten";
  &finish();
}
if (-e "ownergroup_backup.sh"){
  $error= " The backup file \"ownergroup_backup.sh\" already exists\n";
  $error.=" Please rename or remove it as previous backup files will not be overwritten";
  &finish();
}




printf " Preparing backup files \"permissions_backup.sh\" and \"ownergroup_backup.sh\"\n";


system("touch permissions_backup.sh");

if (!open FILE, "+< permissions_backup.sh"){
  $error= " The file \"permissions_backup.sh\" could not be opened";
  &finish();
}
seek FILE,0,0;

#permission backup
sub recdirs_p($);    #prototype needed before
print FILE "#!/bin/bash\n";
print FILE "#THE RESTORATION OF PERMISSIONS STARTS HERE: $startdir\n";
print FILE "#START > ---------------\n";
print FILE "\necho\necho \" Restoring, this may take a while...\"\n";
&recdirs_p($startdir,"");
print FILE "\necho \" Completed\"\necho\n";
print FILE "\n#END < ---------------\n";

#make executable bash script out of it
system ("chmod 00711 permissions_backup.sh");  
close (FILE);

printf " Shell script \"permissions_backup.sh\" created\n";




system("touch ownergroup_backup.sh");

if (!open FILE, "+< ownergroup_backup.sh"){
  $error= " The file \"ownergroup_backup.sh\" could not be opened";
  &finish();
}
seek FILE,0,0;

#owner, group backkup
sub recdirs_og($);    #prototype needed before
print FILE "#!/bin/bash\n";
print FILE "#THE RESTORATION OF OWNERS/GROUPS STARTS HERE: $startdir\n";
print FILE "#START > ---------------\n";
print FILE "\necho\necho \" Restoring, this may take a while...\"\n";
&recdirs_og($startdir,"");
print FILE "\necho \" Completed\"\necho\n";
print FILE "\n#END < ---------------\n";

#make executable bash script out of it 
system ("chmod 00711 ownergroup_backup.sh");  
close(FILE);

printf " Shell script \"ownergroup_backup.sh\" created\n";


&finish();


#functions ------------------------------------------------------------------------------------------------

sub finish(){
  #error output
  if ($error ne "") { 
    printf(" Error(s) occurred:\n%s\n",$error);
  }else{
    printf " Backup completed\n\n";
    printf " You can restore your permissions and owners/groups by running \"./permissions_backup.sh\" and \"./ownergroup_backup.sh\"\n";
  }
  printf "\n";
  #cleanup
  exit();
}


sub recdirs_p($){
  my $path=$_[0];
  if(opendir(DIR, $path)) {
    #get all objects besides . and ..
    my @obj=grep!/^\.$|^\.\.$/,readdir(DIR);  
 
    #all
    my $mode="";
    my $file="";	
    my $full_path="";
    foreach(@obj){
      $file=$path . "/" . $_;
      #ignore softlinks 
      if (-l $file) { next; }
	  
      $mode=(stat($file))[2];	    
      $mode=sprintf("0%o ", $mode & 07777);
      #if necessary fill with leading zeros 
      if (length($mode) < 5){ $mode = '0' x (5 - length($mode)) . $mode; }
      #support for file names with quotes
      $full_path = shell_escape(catfile($path, $_));
      print FILE qq{chmod $mode -- "$full_path"\n};
    }  
 
    #directories
    foreach(@obj) {
      #(-d "file") also recognizes symbolic links, if they point to a directory
      if((-d "$path/$_") && (!-l "$path/$_")) {
        &recdirs_p("$path/$_");
      }
   }
   close DIR;
 }
}


sub recdirs_og($){
  my $path=$_[0];
  if(opendir(DIR, $path)) {
  my @obj=grep!/^\.$|^\.\.$/,readdir(DIR);
 
    my $uname="";
    my $gname="";
    my $file="";
    my $full_path="";
    foreach(@obj){
      $file=$path . "/" . $_;
      if (-l $file) { next; }
      #get username/groupname for uid/gid. if username/groupname don't exist keep uid/gid 
      if (!defined($uname=$unames{((stat($file))[4])})) { $uname=(stat($file))[4]; }	
      if (!defined($gname=$gnames{((stat($file))[5])})) { $gname=(stat($file))[5]; }	
      $full_path = shell_escape(catfile($path, $_));
      print FILE qq{chown $uname:$gname -- "$full_path"\n};
    }  
 
  foreach(@obj) {
    if((-d "$path/$_") && (!-l "$path/$_")) {
      &recdirs_og("$path/$_");
    }
   }
   close DIR;
 }
}


sub shell_escape($){
    my $string = $_[0];
    $string =~ s/([\$"`\\])/\\$1/g;
    return $string;
}

# end of code ----------------------------------------------------------------------------------------------

# 2  
Old 09-13-2007
Quote:
Originally Posted by joangopan
What i need read to do this??
Where start?
seriously, you need to start reading a Perl and a shell programming book.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Having trouble getting my interactive perl script to work properly

So I'm making an interactive perl script, but I can't get it to work properly. I'm trying to make a script that tell the user to input either 'q' or 'Q' to terminate the program, or 'c' to continue it. If they input anything other than those three keys, it should prompt the user again and again... (5 Replies)
Discussion started by: Eric1
5 Replies

2. UNIX for Dummies Questions & Answers

Script without execute permissions will work for a user?

Please help me to understand the issue: Issue: There are shell scripts in a user home directory (/home/user_1) without execute permissions (rw-r--r--) to owner,group and world These shell scripts were able to execute/work previously but its not working now and it says permission denied or... (2 Replies)
Discussion started by: MSK_1990
2 Replies

3. Shell Programming and Scripting

Perl: script to work with files with the same name in different directories

Hi All, I would like to use a Perl (not Bash) script to work with multiple files of the same name in different directories (all in the same parent directory). I tried to create a loop to do so, but it isn't working. My code so far: while (defined(my $file = glob("./*/filename.txt")) or... (1 Reply)
Discussion started by: elgo4
1 Replies

4. Shell Programming and Scripting

Call a Perl script within a bash script and store the ouput in a .txt file

I'm attempting to write a bash script that will create a network between virtual machines. It accepts three arguments: an RSpec that describes the network topology, and two list of machines (servers and clients). I have a (working) Perl script that I want to call. This Perl script takes an RSpec... (6 Replies)
Discussion started by: mecaka
6 Replies

5. Shell Programming and Scripting

Perl script to modify csv file

Hi Friends, I want to convert a csv file into a ordinary .txt file. I am able to convert but I want the output to look as shown below in the .txt file table findhost= { {"xyz","abc"}, {"rxz","mmz"}, {"vrr","nnz"}, } default={"NONE"} My current perl script #!/usr/bin/env perl... (12 Replies)
Discussion started by: dbashyam
12 Replies

6. Shell Programming and Scripting

Generate script perl mail log not work

Dear unix forum members, I'm working on a script that will parse a mail machine's logs and print a list of email addresses in this format: authen@domain.com | sender@domain | recipient@domain exam account1@domain1.com | sender2@domain2.com |... (3 Replies)
Discussion started by: puka
3 Replies

7. Shell Programming and Scripting

Perl - need script for modify lines

Hello, does somebody can make script for me, which replace: ąćę ąćę ąćę (input file) to ace;|;ąćę ace;|;ąćę ace;|;ąćę (output file) (3 Replies)
Discussion started by: Xadrian
3 Replies

8. Shell Programming and Scripting

Modify Perl Script To Send Attachments

Hello, I'm a newbie to the world of programming and so i decided to take up perl. I'm trying to learn how to modify the script below in order to have it sent with attachments. Any suggestions? #!/usr/bin/perl -w use strict; use warnings; my $from = 'xxx@domain.com'; my $to =... (0 Replies)
Discussion started by: xmaverick
0 Replies

9. Shell Programming and Scripting

Modify a perl script to find and count

Hello all !I have two sets of folders that have IP address from two sources.The below perl script I was working with needs some corrections.I am looking for the perl script to identify and count what IP address are found to be duplicated between both files.The format from both files are the same... (4 Replies)
Discussion started by: richsark
4 Replies

10. Shell Programming and Scripting

Need help to modify perl script: Text file with line and more than 1 space

Dear Friends, I am beginner in Perl and trying to find the problem in a script. Kindly help me to modify the script. My script is not giving the output for the last field and followed text (LA: Language English). Input file & script as follows: Input file: Thu Mar 19 2:34:14 EDT 2009 STC... (3 Replies)
Discussion started by: srsahu75
3 Replies
Login or Register to Ask a Question