Skocz do zawartości

Przydatne Skrypty


broda

Rekomendowane odpowiedzi

elo ;)

jak w temacie - idac za ciosem podobnego watku o projektach - proponuje dodawac tutaj swoje skrypty, jesli tylko uwazacie, ze moga sie komus przydac:

 

skrypcior nizej kasuje podane w parametrach pliki/katalogi (rekurencyjnie) przy uzyciu shred'a z parametrem -u

 

#!/bin/bash
if [ $# = 0 ]
then
        echo "$0: musisz podac w parametrze plik lub katalog, który chcesz wymazac"
        exit 1
else
        for i in $*
        do
                if [ -f $i ]
                then
                        find $i -type f -exec bash -c 'shred -u {}' \;
                        echo "$0: $i zostal bezpiecznie skasowany"

                elif [ -d $i ]
                then
                        find $i -type f -exec bash -c 'shred -u {}' \;
                        rm -rfd $i
                        echo "$0: $i zostal bezpiecznie skasowany"

                else
                        echo "$0: podany plik/katalog: $i nie istnieje "
                        exit 1
                fi
        done
fi

 

bym zapomnial - ecik - dzieki za pomoc ;)

 

 

pozdro ;)

Odnośnik do komentarza
Udostępnij na innych stronach

  • 4 weeks later...

skrypt, który skrobnąłem wczoraj - co robi?

oczyszcza drzewa katalogów z plików tymczasowych (pasujących do: "*~"), może komuś się przyda,

czasami używam go do czyszczenia katalogów projektów www

 

#!/bin/bash
if [ $# = 0 ]
then
        echo "$0: musisz podać w parametrze katalogi, które chcesz oczyścić z plików tymczasowych"
        exit 1
else
        for i in $*
        do
                if [ -d $i ]
                then
                        find $i -type d -exec bash -c 'rm {}/*~' \;
                        echo "$0: $i został wyczyszczony z plików tymczasowych"

                else
                        echo "$0: podany katalog: $i nie istnieje "
                        exit 1
                fi
        done
fi

 

p.s. myślałem, że ten wątek rozwinie się inaczej, tzn. że będzie wiecej wklejonych kodzików basha, a mniej offtopicowej paplaniny...

Odnośnik do komentarza
Udostępnij na innych stronach

obiecany skrypt do hurtowej konwersji przy pomocy lame:

 

#!/bin/bash
if [ $# = 0 ]
then
        echo "$0: musisz podać w parametrze katalogi, w których pliki mają być przekonwertowane"
        exit 1
else
        for i in $*
        do
                if [ -d $i ]
                then
                        find $i -type f -exec bash -c 'lame -h -V 6 {}' \;
                        echo "$0: pliki w $i zostały przekonwertowane"

                else
                        echo "$0: podany katalog: $i nie istnieje "
                        exit 1
                fi
        done
fi

 

robimy wowołanie

./skrypt kat1 kat2 kat3...

 

wszystkie parametry jak w skrypcie, nie bawiłem się w podowanie dodatkowych parametrów wywołania, bo to można zmienić w vi bez trudu, nie ma też żadnego kasowania na końcu orginalnych plików, bo to niebezpieczne, hehe ;)

 

skrypt domyślnie konweruje obsługiwane formaty na mp3 w zmiennej jakości (variable, ok. ~128 - ~192), dodam, że mnie taki dźwięk satysfakcjonuje... po szczegóły odsyłam do man lame

 

 

 

 

pozdro

Odnośnik do komentarza
Udostępnij na innych stronach

No jak rzucamy swoje wypociny to może cos takiego sie komus przyda:

 

Skrypt do konfiguracji sieciówek, jak ktoś widzi byki to krzyczeć ;)

 

#!/bin/bash
echo "+---------------------------------+"
echo "| KONFIGURATOR SIECI LINUX FEDORA |"
echo "+---------------------------------+"
read -p "Podaj nazwe karty sieciowej (eth0, eth1, wlan0... itp.): " karta
echo "OBECNE USTAWIENIA KARTY $karta"
echo "------------------------------"
ifconfig $karta
echo "------------------------------"
read
read -p "Podaj adres IP dla karty $karta: " ip
read -p "Podaj maske dla sieci: " maska
read -p "Podaj brame sieci: " brama
read -p "Podaj podstawowy serwer DNS: " dns1
read -p "Podaj zapasowy serwer DNS: " dns2
ifconfig $karta down
ifconfig $karta $ip netmask $maska
route add default gw $brama
echo "nameserver $dns1" > /etc/resolv.conf
echo "nameserver $dns2" >> /etc/resolv.conf
echo "DEVICE=$karta" >> /etc/sysconfig/network-scripts/ifcfg-$karta
echo "BOOTPROTO=static" >> /etc/sysconfig/network-scripts/ifcfg-$karta
echo "ONBOOT=yes" >> /etc/sysconfig/network-scripts/ifcfg-$karta
echo "TYPE=Ethernet" >> /etc/sysconfig/network-scripts/ifcfg-$karta
echo "USERCTL=no" >> /etc/sysconfig/network-scripts/ifcfg-$karta
echo "PEERDNS=yes" >> /etc/sysconfig/network-scripts/ifcfg-$karta
echo "IPV6INIT=no" >> /etc/sysconfig/network-scripts/ifcfg-$karta
echo "IPADDR=$ip" >> /etc/sysconfig/network-scripts/ifcfg-$karta
echo "NETMASK=$maska" >> /etc/sysconfig/network-scripts/ifcfg-$karta
echo "GATEWAY=$brama" >> /etc/sysconfig/network-scripts/ifcfg-$karta
export mac=`ifconfig $karta |grep -e HWaddr | cut -d"r" -f3`
echo "HWADDR=$mac" >> /etc/sysconfig/network-scripts/ifcfg-$karta

ifconfig $karta up

Odnośnik do komentarza
Udostępnij na innych stronach

to i ja wrzuce cos swojego.

 

skrypt sprawdza czy stoja interfejsy eth0 i eth1 (eth0 mam dhcp klient).

nastepnie sprawdza czy jest podana defaultowa bramka w tablicy routingu, poniewaz nie odswieza mi tego klient, czsami dopiero po drugim restarcie sieci jest OK.

 

no nic, moze sie komus przyda.

 

#!/bin/bash
#
# DLA FEDORA CORE 5
#
# Skrypt sluzy do sprawdzenia stanu kart eth0 i eth1, przy czym eth0 to klient DHCP.
# Jesli eth0 nie otrzymal adresu IP, wtedy skrypt restartuje ustawienia sieci,
# jesli po restarcie (_niema_ → nie ma) ORT default-owej bramki w tablicy routingu, siec restartuje sie ponownie.
#
#
# Created by koralm (Karol Mielniczuk [email protected])
#
# GPL License
#
# Version alpha 0.2
#
# Zmienna do ustawieni liczby urzadzen eth w systemie.
ETHNUMBERS=3
#
#
#
ZM=`ifconfig | grep eth | awk '{print $1}'`

for ETHA in $ZM; do
x=`expr $x + 1`
done
if [ "$x" == "$ETHNUMBERS" ]
then echo "Interfejsy OK" >> /dev/null
else service network restart
fi

ruting=`route | sed -e '1,2d' | awk '{print $2}' | grep -v "*"`
if [ "$ruting" == "" ]
then service network restart
else echo "net ok" >> /dev/null
fi

 

--edit--

 

nowa ciut poprawiona wersja

Odnośnik do komentarza
Udostępnij na innych stronach

skrypt wrzuca obrazek na imageshacka

imageshack plik.jpg

[root@uosiumen ~]# cat /bin/imageshack
#!/usr/bin/env python

# ShackShag 0.1.1, 2006-01-06
# http://bachnik.com/projects/shackshag
# Author: Wiktor Bachnik, wiktor at bachnik dot com

# This software is released under GPL license:
# http://www.gnu.org/licenses/gpl.html
# Some inspiration and code snippets were taken from:
# http://aspn.activestate.com/ASPN/Cookbook/...n/Recipe/146306

# You're using this software at your own risk. The author shall not
# be held liable for ANY problems caused by using this software.
# Remember to read ImageShack Terms of Service before using their services
# It can be found at: http://reg.imageshack.us/content.php?page=rules

"""
ShackShag - imageshack batch image uploader.
"""

import sys, os, getopt, httplib, mimetypes

ALLOWED_EXTENSIONS = ('jpeg', 'jpg', 'png', 'gif', 'bmp', 'tif', 'tiff', 'swf')
MAX_FILE_SIZE = 1024 # size in kB
HOST = 'imageshack.us'
SELECTOR = '/'
USER_AGENT = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.12) \
Gecko/20050922 Firefox/1.0.7 (Debian package 1.0.7-1)"
REFERRER = 'http://imageshack.us/'
FORM_MAX_FILE_SIZE = '3145728'
FORM_SUBMIT = 'host it!'
REMOVE_THUMB_BAR_FIELD = ('rembar', '1')
HINT = 'SHELL UPLOADER:'

def get_file_string(response):
 """
 Returns image identification string from the provided HTTPResponse
 object containg server response for the upload request.
 Returns None when the identification string can't be obtained.
 """
 it = iter(response.read().split('\n'))
 try:
   while True:
     line = it.next()
     if line.find(HINT) != -1:
       return it.next().strip()
 except StopIteration:
   return None

def get_file_contents(file_name):
 """
 Returns contents of the file identified by provided file_name
 parameter.
 May raise IOError exception in case of a miserable failure.
 """
 f = open(file_name);
 data = f.read()
 f.close()
 return data

def send_file(file_name, additional_fields):
 """
 Attempts to upload provided file to imageshack.us hosting server.
 Returns identification string of the uploaded image.
 None is returned when upload failed or the identification string can't
 be obtained.
 May raise IOException when provided file can't be accessed properly.
 """

 fields = [
   ('MAX_FILE_SIZE', FORM_MAX_FILE_SIZE),
   ('refer', ''),
   ('brand', ''),
   ('submit', FORM_SUBMIT)
   ]

 fields.extend(additional_fields)

 file_data = ('fileupload', file_name, get_file_contents(file_name))

 content_type, body = encode_multipart_formdata(fields, file_data)

 h = httplib.HTTPConnection(HOST)
 h.putrequest('POST', SELECTOR)
 h.putheader('Content-Type', content_type)
 h.putheader('Content-Length', str(len(body)))
 h.putheader('Referer', REFERRER)
 h.putheader('User-Agent', USER_AGENT)
 h.endheaders()
 h.send(body)

 return get_file_string(h.getresponse())

def encode_multipart_formdata(fields, file_data):
 """
 Returns string containing MIME encoded form fields and file.
 """
 BOUNDARY = '----------HappyHappy__bouNdaRY_$'
 CRLF = '\r\n'
 L = []
 # add additional form fields
 for (key, value) in fields:
   L.append('--' + BOUNDARY)
   L.append('Content-Disposition: form-data; name="%s"' % key)
   L.append('')
   L.append(value)
 # add file
 L.append('--' + BOUNDARY)
 L.append('Content-Disposition: form-data; name="%s"; filename="%s"' \
   % (file_data[0], file_data[1]))
 L.append('Content-Type: %s' % get_content_type(file_data[1]))
 L.append('')
 L.append(file_data[2])
 L.append('--' + BOUNDARY + '--')
 L.append('')
 body = CRLF.join(L)
 content_type = 'multipart/form-data; boundary=%s' % BOUNDARY

 return content_type, body

def get_content_type(filename):
 """
 Returns MIME type for the provided file name.
 """
 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'

def image_details(id_string):
 """
 Returns a hash with all usable parts of the image id string.
 """
 details = {'host': HOST}
 details['node'], details['dir'], details['file'] = id_string.split('/')
 details['file_prefix'], details['file_extension'] = details['file'].split('.')
 return details

def get_direct_url(id_string):
 """
 Returns direct URL to the image identification string.
 """
 return 'http://%s.%s/%s' % (id_string.split('/')[0], HOST, id_string)

def get_thumbnail(id_string):
 """
 Returns thumbnail link for the image identification string.
 """
 return '<a href="http://%(node)s.%(host)s/my.php?image=%(file)s" \
target="_blank"><img src="\
http://%(node)s.%(host)s/%(node)s/%(dir)s/%(file_prefix)s.th.%(file_extension)s" \
border="0" alt="Free Image Hosting at www.ImageShack.us" /></a>' \
 % image_details(id_string)

def get_forum_link(id_string):
 """
 Returns forum hotlink code (full size) for the image identification string.
 """
 return '[url=http://%(host)s]\
[img=http://%(node)s.%(host)s/%(node)s/%(dir)s/%(file)s][/url]' \
 % image_details(id_string)

def write_output(files, id_string):
 """
 Writes image data to the specified output files.
 May rise IOError.
 """
 for op, fp in files:
   if op == '-s':
     print >> fp, get_direct_url(id_string)
   elif op == '-d':
     print >> fp, get_direct_url(id_string)
   elif op == '-t':
     print >> fp, get_thumbnail(id_string)
   elif op == '-f':
     print >> fp, get_forum_link(id_string)

def parse_options():
 """
 Parses command line options. Images and output descriptors lists
 are returned.
 """
 try:
   options, images = getopt.getopt(sys.argv[1:], 'hsrd:t:f:')
   if len(options) == 0:
     # make output to stdout default
     options.append(['-s', ''])
 except getopt.GetoptError, e:
   print >> sys.stderr, 'Error: ', e
   usage()
   sys.exit(1)

 return options, images

def close_files(output):
 """
 Closes all output file descriptors.
 """
 for op, fp in output:
   fp.close()

def usage():
 """
 Prints little usage reference.
 """
 print """
Usage: %s [OPTIONS] <image files>
 -h print this message
 -s use standard output (default when no output files are specified)
 -r remove size/resolution bar from thumbnails
 -d <direct links file>
 -t <thumbnails file>
 -f <forum links file>
 """ % sys.argv[0]

def main():
 """Main function, one to rule them all."""
 try:
   options, images = parse_options()
   additional_fields = []

   output = [] # holds pairs of output type, and file descriptors
   for o, a in options:
     if o in ('-d', '-t', '-f'):
       output.append((o, open(a, 'w')))
     elif o == '-s':
       output.append((o, sys.stdout))
     elif o == '-r':
       additional_fields.append((REMOVE_THUMB_BAR_FIELD));
     elif o == '-h':
       usage()
       close_files(output)
       sys.exit()

   for image in images:
     if image.split('.')[-1].lower() not in ALLOWED_EXTENSIONS:
       raise Exception, '%s: illegal file extension.' % image
     if os.stat(image).st_size < MAX_FILE_SIZE * 1024:
       id_string = send_file(image, additional_fields)
       if id_string != None:
         write_output(output, id_string)
       else:
         print >> sys.stderr, 'Failed to upload file: %s' % image
     else:
       print >> sys.stderr, '%s: file to large, max. size is %s kilobytes.' \
         % (image, MAX_FILE_SIZE)
 except (IOError, OSError), e:
   print >> sys.stderr, '%s: %s' % (e.strerror, e.filename)
 #except Exception, e:
 #  print >> sys.stderr, e
 else:
   # close all open files
   close_files(output)

if __name__ == '__main__':
 main()
[root@uosiumen ~]#

 

wrzuca plik na patebina

cat plik |pastebin

[root@uosiumen ~]# cat /bin/pastebin
#!/usr/bin/env python
#
# pastebin, a script to upload a file to pastebin.ca from the console.
#
# Copyright © 2005 Raphael Slinckx <[email protected]>
#     Thanks to Gustavo J. A. M. Carneiro  <[email protected]>
#
# 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 Street, Fifth Floor, Boston, MA  02110-1301, USA.
#

import getopt, sys, urllib, urllib2, re, pwd, os
try:
       import pygtk
       pygtk.require("2.0")
       import gtk
       import gobject
       WITH_GTK = True
except ImportError:
       WITH_GTK = False

try:
       import gnomevfs, gtksourceview
       WITH_GNOMEVFS = True
except ImportError:
       WITH_GNOMEVFS = False

# General Constants
TYPES = [
"raw", "asterisk", "c", "cpp", "php", "perl", "java", "vb", "csharp",
"ruby", "python", "pascal", "mirc", "pli", "xml", "sql", "scheme",
"ascript", "ada", "apache", "nasm", "asp", "bash", "css", "delphi", "html", "js",
"lisp", "lua", "asm", "objc", "vbnet" ]

NAME_TYPE_DICT = {
"HTML"   : "html",   "CSS" : "css",    "JavaScript" : "js",    "sh"  : "bash",
"Python" : "python", "PHP" : "php",    "Perl"       : "perl",  "SQL" : "sql",
"C"      : "c",      "Ada" : "ada",    "Lua"        : "lua",   "C++" : "cpp",
"Pascal" : "pascal", "C#"  : "csharp", "XML"        : "xml",
"VB.NET" : "vbnet",  "Java": "java",   "Ruby"       : "ruby" }

EXPIRATIONS = [
"", "5 minutes", "10 minutes", "15 minutes", "30 minutes", "45 minutes",
"1 hour", "2 hours", "4 hours", "8 hours", "12 hours", "1 day", "2 days",
"3 days", "1 week", "2 weeks", "3 weeks", "1 month", "2 months", "3 months",
"4 months", "5 months", "6 months", "1 year" ]

POSTDATA = "content=%(content)s&description=%(description)s&type=%(type)s&expiry=%(expiry)s&name=%(name)s&save=0&s=Submit+Post"
URL = "http://en.pastebin.ca/index.php"
URL_PATTERN = re.compile('http://en.pastebin.ca/\d+')

RAW_MODE = False

# The Meat
def got_pastebin_url(url):
       print url

       if WITH_GTK:
               gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD).set_text(url)
               gobject.timeout_add(1000, gtk.main_quit)
               gtk.main()

def paste(content, description="", name="", expiry="", type="raw"):
       payload = POSTDATA % {
               "content" : urllib.quote_plus(content),
               "description" : urllib.quote_plus(description),
               "type" : TYPES.index(type)+1,
               "expiry" : urllib.quote_plus(expiry),
               "name" : urllib.quote_plus(name)
               }
       req = urllib2.Request(URL, payload, {
               "Referer": "http://en.pastebin.ca/",
               "Content-Type": "application/x-www-form-urlencoded",
               "User-Agent": "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.10) Gecko/20050813 Epiphany/1.7.6",
               "Accept-Language": "en",
               "Accept-Charset": "utf-8",
               })
       return urllib2.urlopen(req).read()

def got_error(err):
       sys.stderr.write("%r\n" % err)

def got_page(res):
       matches = URL_PATTERN.findall(res)
       if len(matches) > 0:
               match = matches[0]
               if RAW_MODE:
                       got_pastebin_url(match.replace("pastebin.ca/","pastebin.ca/raw/"))
               else:
                       got_pastebin_url(match)
       else:
               sys.stderr.write("Could not retreive pastebin url\n")

def usage():
       print """=== Pastebin: Usage
$ pastebin [OPTIONS] [FILE]

Print the pastebin.ca URL of the input file

If FILE is omitted content is read from standard input
OPTIONS:
       -h, --help                      Print this help notice.
       -r, --raw                       Retreive raw text URL (default=off).
       -d, --description       The description of the content (default=empty).
       -m, --message           Same as description
       -n, --name                      Your name (default=your unix username).
       -l, --lines                     The line numbers to send starting at 1 (default=1,0)
                                               Ex: 1,12 or 12,36 or 45 or 45,0
       -t, --type                      The type of the content (default="raw")

       Type can be one of:
       raw, asterisk, c, cpp, php, perl, java, vb, csharp,
       ruby, python, pascal, mirc, pli, xml, sql, scheme,
       ascript, ada, apache, nasm, asp, bash, css, delphi, html, js,
       lisp, lua, asm, objc, vbnet

       If type is not specified, an attempt to auto-detect type is made,
       based on file data/extension. Detection is more reliable when giving FILE
       argument than piping directly. This needs modules gnomevfs and gtksourceview

       If you have module gtk, the pastebin url will be placed in your clipboard,
       you can then paste it with ctrl-v as usual.
"""

if __name__ == "__main__":
       if WITH_GNOMEVFS:
               man = gtksourceview.SourceLanguagesManager()
       else:
               man = None

       # Default Values
       content = ""
       description = ""
       name = pwd.getpwuid(os.getuid())[0]
       expiry = ""
       type = "raw"
       start = 1
       end = 0

       try:
               opts, args = getopt.getopt(sys.argv[1:], "hrd:m:n:t:l:", ["help", "raw", "description=", "message=", "name=", "type=", "lines="])
       except getopt.GetoptError:
               usage()
               sys.exit()

       for o, a in opts:
               if o in ("-h", "--help"):
                       usage()
                       sys.exit()
               if o in ("-l", "--lines"):
                       #Parse the line numbers
                       try:
                               lines = a.split(",")
                               if len(lines) == 2:
                                       if lines[0] != "" and lines[1] != "":
                                               start = int(lines[0])
                                               end = int(lines[1])
                                       elif lines[0] == "" and lines[1] != "":
                                               start = 1
                                               end = int(lines[1])
                                       elif lines[0] != "" and lines[1] == "":
                                               start = int(lines[0])
                                               end = 0
                               elif len(lines) == 1:
                                       start = int(lines[0])
                       except Exception:
                               start = 1
                               end = 0

                       if start > end and end != 0 or start < 1 or end < 0:
                               sys.stderr.write('Error with lines numbers, start:%d end:%d\n' % (start, end))
                               sys.exit()

       # Open the file, and read content.
       f = None
       try:
               if len(args) == 0:
                       f = sys.stdin
               else:
                       f = file(args[0], 'r')

               lines = None
               if end == 0:
                       lines = f.readlines()[start-1:]
               else:
                       lines = f.readlines()[start-1:end]

               content = ''.join(lines)
               f.close()
       except Exception, msg:
               sys.stderr.write('Error while reading the file: %s\n' % msg)
               sys.exit()

       # Try to guess file content type if given, and we have GNOMEVFS
       if WITH_GNOMEVFS:
               mimes = [gnomevfs.get_mime_type_for_data(content)]
               if len(args) > 0:
                       mimes.append(gnomevfs.get_mime_type(os.path.abspath(args[0])))

               for mime in mimes:
                       lang = man.get_language_from_mime_type(mime)
                       if lang != None:
                               name = lang.get_name()
                               try:
                                       type = NAME_TYPE_DICT[name]
                                       sys.stderr.write('Using source type "%s"\n' % type)
                               except KeyError:
                                       sys.stderr.write('No pastebin langage matching name "%s"\n' % name)

       # Parse options
       for o, a in opts:
               if o in ("-r", "--raw"):
                       RAW_MODE = True
               elif o in ("-d", "--description") or o in ("-m", "--message"):
                       description = a
               elif o in ("-n", "--name"):
                       name = a
               elif o in ("-t", "--type"):
                       type = a

       #Parameter validation
       if content.strip() == "":
               sys.stderr.write('Content Empty: "%s"\n' % content)
               sys.exit()
       elif not type in TYPES:
               sys.stderr.write('Unknown type: %s\n' % type)
               sys.exit()

       try:
               res = paste(content, description, name, expiry, type)
               got_page(res)
       except Exception, msg:
               got_error(msg)

Odnośnik do komentarza
Udostępnij na innych stronach

skrypt wyszukuje plik .hushlogin nastepnie wyrzuca wszystkie znalezione i do pliku zapisuje nam ktory uzytkownik stowrzyl ten plik.

 

mam dwie wersje:

 

1 by koralm:

#!/bin/bash
find /home -name '.hushlogin' -exec rm -f {} \; -exec echo {} >> ~/users.hush \;

 

2:

#!/bin/bash
for x in /home/*
do
if [ -f $x/.hushlogin ]
then
rm -f $x/.hushlogin
echo $x >> ~/users.hush
fi
done

Odnośnik do komentarza
Udostępnij na innych stronach

Cos do oblugi ProFTPd pod FC5.

 

nie wiem czy to cos nie ma skryptu czy u mnie wyparowal. mniejsza o to. nadrapalem cos swojego.

porawki i rozbudowy mile widziane.

 

#!/bin/bash
#
# DLA FEDORA CORE 5
#
# Skrypt sluzy do oblugi proFTPd
#
#
# Created by koralm (Karol Mielniczuk [email protected])
#
# GPL License
#
# Version beta 0.1
#
#

ZMPFTP=`ps aux | grep proftp | awk '{print $11}' | sed -e '2d' | sed -n -e 's/proftpd:/proftpd/p'`
if [ "$ZMPFTP" == "proftpd" ]
then
pidftp=`cat /usr/local/var/proftpd.pid`

if [ "$1" == "" ]
then
	echo "ProFTPd jest uruchomiony"
else
	if [ -f /etc/shutmsg ]
	then
		rm -f /etc/shutmsg
	fi
fi

else
if [ "$1" == "" ]
	then
		echo "ProFTPd nie jest uruchomiony"
fi
fi

start()
{
echo "ProFTPd startuje...."
/usr/local/sbin/proftpd
}

stop()
{
echo "ProFTPd wylacza sie...."
kill -9 $pidftp
}

restart()
{
echo "Restartowanie ProFTPd...."
stop
sleep 3
start
}

status()
{
# Wczytanie tablicy userow zalogowanych na FTP i wyswietlenie.
CZASDZIALANIA=`ftpwho | head -1 | awk '{print $7$8$9$10}'`

for FLUSER in `ftpwho | sed -e '1d' | awk '{print $1,$2,$4,$5}' | sed -n -e 's/]//p' | awk '{print $2}'`; do
w=`expr $w + 1`
FTP_L[$w]=$FLUSER
done

for FPIDUSER in `ftpwho | sed -e '1d' | awk '{print $1,$2,$4,$5}' | sed -n -e 's/]//p' | awk '{print $1}'`; do
x=`expr $x + 1`
FTP_P[$x]=$FPIDUSER
done

for FTIME in `ftpwho | sed -e '1d' | awk '{print $1,$2,$4,$5}' | sed -n -e 's/]//p' | awk '{print $3}'`; do
y=`expr $y + 1`
FTP_T[$y]=$FTIME
done

for FIDLE in `ftpwho | sed -e '1d' | awk '{print $1,$2,$4,$5}' | sed -n -e 's/]//p' | awk '{print $4}'`; do
z=`expr $z + 1`
FTP_I[$z]=$FIDLE
done

echo ""
echo "ProFTPD dziala juz $CZASDZIALANIA - PID:$pidftp"
echo ""

if [ "${FTP_L[*]}" == "" ]
then
	if [ "${FTP_P[*]}" == "" ]
	then
			if [ "${FTP_T[*]}" == "" ]
			then
					if [ "${FTP_I[*]}" == "" ]
					then
							echo "Brak uzytkownikow korzystajacych z FTP"
							echo ""
					fi
			fi
	fi
else
for all in `seq 1 $z`; do
echo "LOGIN:${FTP_L[$all]}	  | PID:${FTP_P[$all]}	| Czas polaczenia:${FTP_T[$all]}		| Czas bezczynnosci:${FTP_I[$all]}"
done
fi
}

case $1 in
"START"|"start")
start
;;
"STOP"|"stop")
stop
;;
"RESTART"|"restart")
restart
;;
"STATUS"|"status")
status
;;
*)
echo "Uzyj odpowiednio START | STOP | RESTART | STATUS"
;;
esac

Odnośnik do komentarza
Udostępnij na innych stronach

Cos do oblugi ProFTPd pod FC5.

 

Pytanie brzmi: po co? proftpd z paczki ma już coś takiego -> http://cvs.fedora.redhat.com/viewcvs/rpms/...amp;view=markup (nikt o zdrowych zmysłach nie będzie instalował przez "make install").

 

Poza tym pod względem bezpieczeństwa i wydajności proftpd ustępuje vsftpd. Nie bez powodu vsftpd jest domyślnym serwerem ftp m. in. w OpenBSD...

http://vsftpd.beasts.org/#people

Odnośnik do komentarza
Udostępnij na innych stronach

Jeśli chcesz dodać odpowiedź, zaloguj się lub zarejestruj nowe konto

Jedynie zarejestrowani użytkownicy mogą komentować zawartość tej strony.

Zarejestruj nowe konto

Załóż nowe konto. To bardzo proste!

Zarejestruj się

Zaloguj się

Posiadasz już konto? Zaloguj się poniżej.

Zaloguj się
×
×
  • Dodaj nową pozycję...