27 Ekim 2020 Salı

asprintf metodu

Giriş
Bu metod tüm platformlarda yoktur

Örnek
Şöyle yaparız
char* defangIPaddr(const char* address)
{
    char* defanged;
    int ip[4];

    if (sscanf(address, "%d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3]) != 4)
        return NULL;

    if (asprintf(&defanged, "%d[.]%d[.]%d[.]%d", ip[0], ip[1], ip[2], ip[3]) == -1)
        return NULL;

    return defanged;
}

ip link komutu - Arayüzleri Gösterir

Giriş
Arayüzleri gösterir.

ip komutu ile birlikte birçok object kullanılabilir. Bunlar şöyle
linkaddr, addrlabel, route, rule, neigh, tunnel,  maddr, mroute, monitor.

Örnek
Şöyle yaparız
root@box:/# ip link show

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 ...
2: eno3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 ... 
3: eno1np0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 ...
4: eno2np1: <BROADCAST,MULTICAST> mtu 1500 ...

22 Ekim 2020 Perşembe

expect komutu - Kurulum Esnasında Sorulara Cevap Verir

Giriş
Otomasyon için çok faydalıdır. Kurulum tarzı bir uygulamanın istediği girdileri sağlayabilir 

Örnek
Şöyle yaparız
#!/usr/bin/expect
spawn sudo apt-get -y install cuda
expect "first prompt:"
send "31\r"
expect "second prompt:"
send "1\r"
wait

NetworkManager Servisi - Ubuntu

Giriş
NetworkManager, ağ (network) ayarlarını yöneten servistir. Eskinde bu servisin ismi "network-manager" idi

Masaüstünden Erişmek
Hem Gnome, hem de Unity masaüstünden sağ üst koşeden erişilebilir

Terminalden Erişmek
Bu servisin ayarları /etc/NetworkManager dizininden. Örneğin bağlantılar (connections) /etc/NetworkManager/system-connections/ dizininde

Ayarların Devreye Girmesi
Masaüstünden bir ayar değiştirdikten sonra bu ayarın devreye girdiğinden emin olmak için NetworkManager servisini tekrar başlatmak gerekir. Kullanmak için şöyle yaparız
sudo service NetworkManager start|stop|...
sudo systemctl start|stop|... NetworkManager
sudo systemctl start|stop|... NetworkManager.service
Örnek
Şöyle yaparız
sudo systemctl restart NetworkManager

19 Ekim 2020 Pazartesi

sshfs komutu

Giriş
Açıklaması şöyle
Mac and Linux computers can connect to each other easily with SSH. Using sshfs I can securely mount remote folders, browse them freely and copy files.
Örnek
Şöyle yaparız
sshfs tomasz@macbook.local:/Users/tomasz ~/macbook/tomasz

12 Ekim 2020 Pazartesi

jq komutu - JSON processor

Giriş
Açıklaması şöyle
... jq is a command-line tool for parsing and manipulating JSON data. It is written in C and has a lightweight, minimalistic and flexible syntax. It allows you to filter, extract, and transform JSON data quickly and easily, making it a powerful tool for data processing and analysis.

jq was created by Steve Kemp. He started working on jq in early 2011, and the first version was released in April of that year. The tool quickly gained popularity among developers and data analysts, and it has since become one of the most widely used command-line JSON processors.
jq Filters
Açıklaması şöyle
jq reads JSON data from input and applies a series of filters to it, producing one or more outputs. The filters are written in a domain-specific language (DSL) that is similar to the one used in functional programming languages like Haskell, Lisp and Ruby.
Açıklaması şöyle
jq supports a wide range of filter types that can be used to select, extract, and modify JSON data, common ones are:

Selectors: Select specific parts of JSON data.
Functions: Built-in functions that can be used to perform various operations on the input JSON data.
Operators: Used to perform mathematical, logical, and comparison operations on the input JSON data.
Pipe: Used to connect multiple filters together, where the output of one filter is passed as input to the next filter.
jq Data Types
Açıklaması şöyle
jq supports several types of data, including:

Numbers: Integers and floating-point values, such as 42, 3.14, and -2.
Strings: Text enclosed in double quotes, such as “hello world”.
Booleans: true and false.
Arrays: Lists of values enclosed in square brackets, such as [1, 2, 3].
Objects: Key-value pairs enclosed in curly braces, such as {“name”: “Tony”, “age”: 100}.
Null: The special value null.
jq Regular Expression
Açıklaması şöyle
jq uses the Oniguruma regular expression library, as do php, ruby, TextMate, Sublime Text, etc, so the description here will focus on jq specifics.

The jq regex filters are defined so that they can be used using one of these patterns:

STRING | FILTER( REGEX )
STRING | FILTER( REGEX; FLAGS )
STRING | FILTER( [REGEX] )
STRING | FILTER( [REGEX, FLAGS] )
Örnek
Şöyle yaparız
$ cat file.json | jq '.[] | select(.email | test("^[a-z]+@"))'

$ cat file.json | jq '.[] | select(.email | test("^[a-z]+@") | not)'

Örnek
Pretty print için şöyle yaparız
kubectl get 
  --raw "..." 
  | jq .
Örnek
Şöyle yaparız
$ echo '{"name": "Tony", "age": 100}' | jq .
{
  "name": "Tony",
  "age": 100
}
Identifier Yani Key
Örnek
Şöyle yaparız
$ echo '{"foo": 42, "bar": "less interesting data"}'  | jq '.foo'
42
İsimli Array
Örnek
Elimizde şöyle bir JSON olsun
{
  "DBClusterSnapshots": [
    {
      ...
      "Status": "copying",
      ...
    }
  ]
}
Status alanına erişmek için şöyle yaparız
jq -r .DBClusterSnapshots[0].Status
Bir diğer seçenek olarak Şöyle yaparız
jshon -e DBClusterSnapshots -e 0 -e Status -u
İsimsiz Array
.[N] veya .[N] şeklinde kullanılır. Array'in içindeki bir alana erişmek için .[].keyname şeklinde kullanılır
Örnek
Şöyle yaparız
$ echo '[1, 2, 3]' | jq '.[1]'
2
Örnek
Şöyle yaparız
$ echo '[{"name": "Tony", "age": 100}, {"name": "Jane", "age": 25}]' | jq '.[].name'
"Tony"
"Jane"
Örnek
Elimizde şöyle bir kod olsun. url kısmı önemli değil.
~ curl -X GET -H "Accept: application/vnd.kafka.avro.v2+json" \
      http://localhost:... | jq

[
  {
    "topic": "movies",
    "key": null,
    "value": {
      "id": 294,
      "title": "Die Hard",
      "release_year": 1988
    },
    "partition": 0,
    "offset": 0
  },
  ...
]
Bu çıktıdan sadece "title" ve "release year" alanlarını isteyelim. Şöyle yaparız. İsmisiz array nesnesinin içindeki tüm title vs gibi alanlara erişilir
~ curl -X GET -H "Accept: application/vnd.kafka.avro.v2+json" \
      http://localhost:... | jq \
      | jq '.[] | {title: .value.title, year: .value.release_year}'

{
  "title": "Die Hard",
  "year": 1988
}
{
  "title": "Tree of Life",
  "year": 2011
}
{
  "title": "A Walk in the Clouds",
  "year": 1995
}
{
  "title": "The Big Lebowski",
  "year": 1998
}
{
  "title": "Super Mario Bros.",
  "year": 1993
}
{
  "title": "Chariots of Fire",
  "year": 1981
}
keys function
Örnek
Şöyle yaparız
$ echo '{"name": "Tony", "age": 100}' | jq 'keys'
[
  "age",
  "name"
]
length function
Örnek
Şöyle yaparız
$ echo '[1, 2, 3]' | jq 'length'
3
to_entries function
Örnek
Şöyle yaparız
$ echo '{"name": "Tony", "age": 100}' | jq 'to_entries | .[] | .value'
"Tony"
100
Conditionals and Comparisons
select(.keyname) şeklindedir

Örnek
Şöyle yaparız
$ cat file.json | jq '.[] | select(.name == "Tony")'

$ cat file.json | jq '.[] | select(.age > 100)'

$ cat file.json | jq '.[] | select(.age >= 100)'

$ cat file.json | jq '.[] | select(.age > 100 and .gender == "male")'

$ cat file.json | jq '.[] | select(.age > 100 or .gender == "female")'
--args seçeneği
array oluşturur
Örnek
Şöyle yaparız
{
jq -n --arg key APP-Service1-Admin '{($key): $ARGS.positional}' --args a b jq -n --arg key APP-Service1-View '{($key): $ARGS.positional}' --args c d } // Output { "APP-Service1-Admin": [ "a", "b" ] } { "APP-Service1-View": [ "c", "d" ] }

--join-output seçeneği
Örnek
Şöyle yaparız
$ ip -details -json link show | jq --join-output '...'
-r seçeneği 
Şöyle yaparız
jq -r '.Policy'

4 Ekim 2020 Pazar

Ubuntu Sürümleri

LTS Ne Demek
Long Term Support anlamına gelir. Yazılımın az çökeceği anlamına dolaylı olarak gelir. Esas anlamı yazılımın artık az değişeceği anlamına gelmesidir. Açıklaması şöyle
Don't confuse support and stability.

LTS releases offer "stability" in the sense that the software does not change for 5 years, not the sense that it crashes less often. The latter coincidentally does happen to be somewhat true also, but that's due to the large user base discovering and filing bugs.
Dolayısıyla LTS sürümü en yeni yazılımı kurmak için kullanmanın anlamı yok. Açıklaması şöyle
A common problem occurs when folks mistakenly consider an LTS to be a "stable base system" that they can bolt newer software onto. This is precisely the opposite of what an LTS is designed for. If you want newer software, use a newer release of Ubuntu. The Interim (6-month) releases are just as stable for most users as LTS... AND have newer kernel and software.

Sürüm Numaraları
12.04, 14.04, 16.04 gibi sayılar kullanılır. 04 Nisan ayında sürüm çıktığını gösterir. Baştaki sayı ise senedir.

Örnek
LTS ile paketlerin ne zaman kadar destekleneceğini görmek için şöyle yaparız
$ ubuntu-security-status 
2258 packages installed, of which:
1745 receive package updates with LTS until 4/2025
 499 could receive security updates with ESM Apps until 4/2030
   1 package is from a third party
  13 packages are no longer available for download


bash kodlama - Subshell

Giriş
Bash ile subshell kullanmanın 3 yöntemi var.
1. (...) şeklinde kullanmak
2. <(...) şeklinde process substitution şeklinde kullanmak
3. "$(...)" şeklinde command substitution şeklinde kullanmak

2 ve 3 numaralar da subshell içinde çalışır. Açıklaması şöyle
A command substitution $(...) will be replaced by the output of the command, while a process substitution <(...) will be replaced by a filename from which the output of the command may be read. The command, in both instances, will be run in a subshell.
(...) ve {...} Farklı Şeylerdir - Subshell vs Curly Braces
Açıklaması şöyle
(list)

list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below). Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list.
Diğer açıklama şöyle
{ list; }

list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is known as a group command. The return status is the exit status of list. Note that unlike the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized. Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharacter.
Örnek
Elimizde şöyle bir kod olsun. Burada or opertor'den sonra gelen kod subshell içinde çalışır ve exit status var olduğu için gösterilebilir.
no_func || (
    echo "there is nothing"
    exit 1
)

echo $?
Çıktı olarak şunu alırız
$ ./script1.sh
./script1.sh: line 3: no_func: command not found
there is nothing 
1 # <-- exit status of subshell
$ echo $?
0 # <-- exit status of script
Kodu değiştirelim ve subshell yerine curly brace kullansın. Şöyle olsun
no_func || {
    echo "there is nothing"
    exit 1
}

echo $?
Çıktı olarak şunu alırız. Bu sefer subshell yoktur ve exit 1 ile tüm betik sonlanır. Bu yüzden "echo $?" komutu da çalışmaz.
/Users/myname/bin/ex5: line 34: no_func: command not found
there is nothing
Subshell Parent Shell'in Ortam Değişkenlerini Görebilir
Açıklaması şöyle
The parentheses () open a new subshell that will inherit the environment of its parent. However, the subshell will exit as soon as the commands running it it are done, returning you to the parent shell and the cd will only affect the subshell, therefore your PWD will remain unchanged.

However, note that the subshell will also copy all shell variables, so you cannot pass information back from the subshell function to the main script via global variables.
Örnek
Eğer bir metod içinde yapmak istersek şöyle yaparız
doStuffAt() (
  cd -- "$1" || exit # the subshell if cd failed.
  # do stuff
)

systemctl komutu - Ubuntu Kullanır

Giriş
systemctl "Service Manager" olarak düşünülmeli. systemd kullanan işletim sistemlerindeki komutlardan bir tanesi systemctl. Açıklaması şöyle.
systemd gives us the systemctl command which is mostly used to enable services to start at boot time. We can also start, stop, reload, restart and check status of services with the help of systemctl.

We can do sudo systemctl enable service_name, and the service will automatically start at boot time. We can also disable services not to start at boot time.
Ubuntu 15.04'ten itibaren bu yapıya geçmeye başladı.

servisismi.service dosyası
Systemd İçin Service Dosyası yazısına taşıdım.

Bash Ornekleri
Örnek
Şöyle yaparız
#!/bin/sh

service=$1
if 
  systemctl | grep -q "$service"
then
  systemctl status "$service"
else
  echo "The service doesn't exist"
fi
Komut Satırı Seçenekleri
Giriş
Kullanım : systemctl + seçenek + servis_ismi şeklindedir.

daemon-reload seçeneği
/etc/systemd/system/ dizini altındaki dosyalarda bir ayar değiştiyse kullanılır. Şöyle yaparız.
systemctl daemon-reload
Daha sonra yeni servisi veya değişen servisi tekrar durdurup başlatmak gerekir. Şöyle yaparız
sudo systemctl start zookeeper
sudo systemctl status zookeeper
disable seçeneği
Açıklaması şöyle.
Running systemctl disable removes the symlink to the service in /etc/systemd/system/*.
From now on, that service won't start on boot anymore.
Örnek
Şöyle yaparız.
systemctl disable snmpd
Örnek
Şöyle yaparız.
sudo systemctl disable apache2
enable seçeneği
Örnek
Şöyle yaparız.
sudo systemctl enable /etc/systemd/system/macoverride.service
Örnek
Eğer tek bir komut ile enable + start yapmak istersek şöyle yaparız
systemctl enable --now
is-active seçeneği
Örnek
Şöyle yaparız.
systemctl is-active --quiet myservice
Örnek
Şöyle yaparız.
systemctl is-active --quiet service && echo Service is running
isolate seçeneği
Kendi dosyamı çalıştırmak için şöyle yaparız.
# systemctl isolate maintenance.target
Belli bir seviyedeki servisleri çalıştırmak için şöyle yaparız.
# systemctl isolate multi-user.target
list-unit seçeneği
Açıklaması şöyle
systemd units can be listed with systemctl list-units for currently active and systemctl -a list-units for all known units.
Örnek
Şöyle yaparız.
systemctl list-units | grep -E 'service.*running'
mask seçeneği
Örnek - poweroff yeteneğini iptal etme
Şöyle yaparız
sudo systemctl mask poweroff.target
...
sudo systemctl unmask poweroff.target
reboot seçeneği
UEFI (Unified Extensible Firmware Interface) ekranına girebilmeyi sağlar.
Örnek
Şöyle yaparız
systemctl reboot --firmware-setup
restart seçeneği
Örnek
Şöyle yaparız.
systemctl restart NetworkManager
Örnek
Şöyle yaparız.
systemctl restart sshd
show seçeneği
Açıklaması şöyle.
Show properties of one or more units, jobs, or the manager itself. If no argument is specified, properties of the manager will be shown. If a unit name is specified, properties of the unit are shown, and if a job ID is specified, properties of the job are shown. By default, empty properties are suppressed. Use --all to show those too. To select specific properties to show, use --property=. This
command is intended to be used whenever computer-parsable output is required. Use status if you are looking for formatted human-readable output.
Şöyle yaparız.
$ systemctl show -p SubState --value NetworkManager
running
Şöyle yaparız.
$ systemctl show -p ActiveState --value x11-common
inactive
$ systemctl show -p SubState --value x11-common
dead
start seçeneği
Şöyle yaparız.
systemctl enable ssmatt.service
systemctl start ssmatt.service
status seçeneği
Örnek
Tüm servisleri görmek için şöyle yaparız.
systemctl status
Çıktı olarak ağaç yapısı alırız.
├─systemd-journald.service
         │ └─318 /lib/systemd/systemd-journald
         ├─fwupd.service
         │ └─1703 /usr/lib/fwupd/fwupd
         ├─systemd-networkd.service
         │ └─395 /lib/systemd/systemd-networkd
         └─cups-browsed.service
           └─2918 /usr/sbin/cups-browsed
lines 172-194/194 (END)
Örnek - servis ismi
Servis ismi olarak x.service ye da sadece x kullanılabilir.

Şöyle yaparız.
systemctl status bluetooth
 bluetooth.service - Bluetooth service
  Loaded: loaded ...
  Active: inactive (dead)
     Docs: man:bluetoothd(8)
Şöyle yaparız
systemctl status sshd
Örnek - pid
Elimizde şöyle bir bilgi olsun.
systemd(1)───foo(37775)─┬─{foo1}(37782)
                        ├─{foo2}(37783)
                        └─{foo3}(37784)
Şöyle yaparız.
$ systemctl status 37775
stop seçeneği
Örnek
Şöyle yaparız
systemctl stop snmpd
Örnek
Normalde şöyle yapmak gerekir.
systemctl stop media-backup.automount
servis ismi için dosya yolu kullanmak istersek şöyle yaparız.
systemctl stop "$(systemd-escape -p --suffix=automount /media/backup)"
-t seçeneği
type anlamına gelir. Açıklaması şöyle.
-t, --type=
       The argument should be a comma-separated list of unit types such as
       service and socket.

       If one of the arguments is a unit type, when listing units, limit
       display to certain unit types. Otherwise, units of all types will
       be shown.

       As a special case, if one of the arguments is help, a list of
       allowed values will be printed and the program will exit.

   --state=
       The argument should be a comma-separated list of unit LOAD, SUB, or
       ACTIVE states. When listing units, show only those in the specified
       states. Use --state=failed to show only failed units.

       As a special case, if one of the arguments is help, a list of
       allowed values will be printed and the program will exit.
Çalışmakta olan servisleri görmek için şöyle yaparız.
systemctl --type=service --state=running list-units
--user seçeneği
Sistem service manager" yerine kullanıcının "service manager" uygulamasını kullanmak için şöyle yaparız.
systemctl --user enable my_example.service
systemctl --user start my_example.service
...
systemctl --user stop my_example.service
systemctl --user status my_example.service