Monthly Archives: 9月 2015

Linuxでプロセスごとのメモリ使用量を確認するシェルコード

コード下記
echo -e “PID\t\tMem\t\tProc_Name”
for pid in `ls -l /proc | grep ^d | awk ‘{ print $NF }’| grep -v [^0-9]`
do
if [ $pid -eq 1 ];then continue;fi
grep -q “Rss” /proc/$pid/smaps 2>/dev/null
if [ $? -eq 0 ];then
swap=$(grep Rss /proc/$pid/smaps \
| gawk ‘{ sum+=$2;} END{ print sum }’)
proc_name=$(ps aux | grep -w “$pid” | grep -v grep \
| awk ‘{ for(i=11;i<=NF;i++){ printf(“%s “,$i); }}’)
if [ $swap -gt 0 ];then
echo -e “${pid}\t${swap}\t${proc_name}”
fi
fi
done | sort -k2 -n | awk -F’\t’ ‘{
pid[NR]=$1;
size[NR]=$2;
name[NR]=$3;
}
END{
for(id=1;id<=length(pid);id++)
{
if(size[id]<1024)
printf(“%-10s\t%15sKB\t%s\n”,pid[id],size[id],name[id]);
else if(size[id]<1048576)
printf(“%-10s\t%15.2fMB\t%s\n”,pid[id],size[id]/1024,name[id]);
else
printf(“%-10s\t%15.2fGB\t%s\n”,pid[id],size[id]/1048576,name[id]);
}
}

rsync+inotifyでHPリソースを自動的にバックアップする

1.サーバ環境
マスター(master)サーバ:192.168.5.87 inotify
スレーブ(slave)サーバ:192.168.6.88 rsync

2.slaveサーバにrsyncをインストール
um -y install rsync
vim /etc/rsyncd.conf
uid = nginx
gid = nginx
port = 873
host all = 192.168.6.87
use chroot = on
max connections = 4
timeout = yes
[wordpress]
path = /usr/local/nginx/html/wordpress
comment = rsync files
ignore errors
read only = no
list = yes
auth users = rsync
secrets file = /etc/rsync.passwd
vim /etc/rsync.passwd
#ユーザ:パスワード
rsync:rsync

3. master サーバーにinotify-toolsをインストール
wget https://github.com/rvoicilas/inotify-tools/archive/v3.14.tar.gz
tar -zxvf inotify-tools-3.14.tar.gz
cd inotify-tools-3.14
./configure –prefix=/usr/local/inotify
make && make install

vim /etc/rsync.passwd
#パスワード
rsync

4.shellコード
vim inotifyrsync.sh
#!/bin/bash
host=192.168.6.88
src=/usr/local/nginx/html/wordpress/
dst=wordpress
user=rsync
inotifywait=/usr/local/inotify/bin/inotifywait
rsync=/usr/bin/rsync
$inotifywait -mrq –timefmt ‘%d/%m/%y %H:%M’ –format ‘%T %w%f’ -e modify,delete,create,attrib $src | while read files
do
$rsync -vzrtopg –delete –progress –password-file=/etc/rsync.passwd $src $user@$host::$dst
echo “${files} was rsynced” >>/tmp/rsync.log 2>&1
done

「nginx」ngx_http_upstream_consistent_hashジュールをインストール、配置方法

1.インストール
# wget https://github.com/replay/ngx_http_consistent_hash/archive/master.zip
# unzip master.zip
# ./configure –add-module=./3thparty/ngx_http_consistent_hash-master
# make
# make install

2.設定
consistent_hash $request_uri;
server 172.31.27.2:10401;
server 172.31.27.3:10401;
server 172.31.27.4:10401;
}


server {
listen 80;
server_name localhost;

location / {
default_type text/html;
set $memcached_key $request_uri;
memcached_pass somestream;
error_page 500 404 405 = @fallback;
}
location @fallback {
root /var/www/howen;
fastcgi_intercept_errors on;
error_page 404 = @404;
set $script $uri;
set $path_info “”;
include /usr/local/nginx/conf/fastcgi_params;
fastcgi_param SCRIPT_FILENAME /var/www/howenr/checktt.php;
fastcgi_param SCRIPT_NAME $script;
fastcgi_param REQUEST_URI $uri;
fastcgi_pass 127.0.0.1:9000;
}
}

Javaでチャネル「Java.nio.channels.Pipe」を利用する方法

サンプルコード
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

public class PipeStartnews24 {
public static void main(String[] args) {
//初期化
Pipe pipe = null;
try {
pipe = Pipe.open();
} catch (IOException e) {
e.printStackTrace();
}
Pipe.SinkChannel skChannel = pipe.sink();
String testData = “start to check java NIO Channels Pipe”;

ByteBuffer buffer = ByteBuffer.allocate(512);
buffer.clear();
buffer.put(testData.getBytes());

buffer.flip();
//データを書き込み
while(buffer.hasRemaining()) {
try {
skChannel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
//データを読み込む
Pipe.SourceChannel sourceChannel = pipe.source();
buffer = ByteBuffer.allocate(512);
//コンソールにデータを出力
try {
while(sourceChannel.read(buffer) > 0){

buffer.flip();

while(buffer.hasRemaining()){
char ch = (char) buffer.get();
System.out.print(ch);
}
buffer.clear();
}
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
}

Linuxでarp-scan1.9をインストール、競合IPを判断する方法

1.libpcapとlibcap-develのインストール
[root@localhost src]# yum install -y libcap libcap-devel
[root@localhost arp-scan-1.9]# yum list|grep libpcap
libpcap.x86_64 14:1.4.0-1.20130826git2dbcaa1.el6
libpcap-devel.x86_64 14:1.4.0-1.20130826git2dbcaa1.el6
libpcap.i686 14:1.4.0-4.20130826git2dbcaa1.el6
libpcap.x86_64 14:1.4.0-4.20130826git2dbcaa1.el6
libpcap-devel.i686 14:1.4.0-4.20130826git2dbcaa1.el6
libpcap-devel.x86_64 14:1.4.0-4.20130826git2dbcaa1.el6

2.arp-scan1.9のダウンロード
[root@localhost src]# wget http://www.nta-monitor.com/files/arp-scan/arp-scan-1.9.tar.gz

3.arp-scan1.9のインストール
tar xvf arp-scan-1.9.tar.gz
cd arp-scan-1.9
./configure
make && make install

4.シェルコード:
#!/bin/bash
#check whether the ip is conflict
conflict_ip=`arp-scan -I eth0 -l | grep “^[172.16|192.168|10]” | sort | uniq -c | sort -nr|sed ‘s/^[ \t]*//g’|grep “^2″`

count=`arp-scan -I eth0 -l | grep “^[172.16|192.168|10]” | sort | uniq -c | sort -nr|sed ‘s/^[ \t]*//g’|grep “^2″|wc -l`
if [ $count -gt 0 ];then
echo -e “\033[31m conflict \033[0m”
echo -e “conflict ip is \n $conflict_ip ”
else
echo “not conflict.”
fi

「Objective-C」iosデバイスのIPアドレスを取得する方法

参考コード:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/sockio.h>
#include <net/if.h>
#include <errno.h>
#include <net/if_dl.h>
//#include “GetAddresses.h”
#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))
#define BUFFERSIZE 4000
char *if_names[MAXADDRS];
char *ip_names[MAXADDRS];
char *hw_addrs[MAXADDRS];
unsigned long ip_addrs[MAXADDRS];
static int nextAddr = 0;
void InitAddresses()
{
int i;
for (i=0; i<MAXADDRS; ++i)
{
if_names[i] = ip_names[i] = hw_addrs[i] = NULL;
ip_addrs[i] = 0;
}
}
void FreeAddresses()
{
int i;
for (i=0; i<MAXADDRS; ++i)
{
if (if_names[i] != 0) free(if_names[i]);
if (ip_names[i] != 0) free(ip_names[i]);
if (hw_addrs[i] != 0) free(hw_addrs[i]);
ip_addrs[i] = 0;
}
InitAddresses();
}
void GetIPAddresses()
{
int i, len, flags;
char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
struct ifconf ifc;
struct ifreq *ifr, ifrcopy;
struct sockaddr_in *sin;
char temp[80];
int sockfd;
for (i=0; i<MAXADDRS; ++i)
{
if_names[i] = ip_names[i] = NULL;
ip_addrs[i] = 0;
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
perror(“socket failed”);
return;
}
ifc.ifc_len = BUFFERSIZE;
ifc.ifc_buf = buffer;
if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0)
{
perror(“ioctl error”);
return;
}
lastname[0] = 0;
for (ptr = buffer; ptr < buffer + ifc.ifc_len; )
{
ifr = (struct ifreq *)ptr;
len = max(sizeof(struct sockaddr), ifr->ifr_addr.sa_len);
ptr += sizeof(ifr->ifr_name) + len; // 次のバッファ
if (ifr->ifr_addr.sa_family != AF_INET)
{
continue; // ignore if not desired address family
}
if ((cptr = (char *)strchr(ifr->ifr_name, ‘:’)) != NULL)
{
*cptr = 0; // コロンを交換してnull結果
}
if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0)
{
continue; /* インタフェースを処理済み */
}
memcpy(lastname, ifr->ifr_name, IFNAMSIZ);
ifrcopy = *ifr;
ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);
flags = ifrcopy.ifr_flags;
if ((flags & IFF_UP) == 0)
{
continue; //インターフェースを無視
}
if_names[nextAddr] = (char *)malloc(strlen(ifr->ifr_name)+1);
if (if_names[nextAddr] == NULL)
{
return;
}
strcpy(if_names[nextAddr], ifr->ifr_name);
sin = (struct sockaddr_in *)&ifr->ifr_addr;
strcpy(temp, inet_ntoa(sin->sin_addr));
ip_names[nextAddr] = (char *)malloc(strlen(temp)+1);
if (ip_names[nextAddr] == NULL)
{
return;
}
strcpy(ip_names[nextAddr], temp);
ip_addrs[nextAddr] = sin->sin_addr.s_addr;
++nextAddr;
}
close(sockfd);
}
void GetHWAddresses()
{
struct ifconf ifc;
struct ifreq *ifr;
int i, sockfd;
char buffer[BUFFERSIZE], *cp, *cplim;
char temp[80];
for (i=0; i<MAXADDRS; ++i)
{
hw_addrs[i] = NULL;
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
perror(“socket failed”);
return;
}
ifc.ifc_len = BUFFERSIZE;
ifc.ifc_buf = buffer;
if (ioctl(sockfd, SIOCGIFCONF, (char *)&ifc) < 0)
{
perror(“ioctlエラー”);
close(sockfd);
return;
}
ifr = ifc.ifc_req;
cplim = buffer + ifc.ifc_len;
for (cp=buffer; cp < cplim; )
{
ifr = (struct ifreq *)cp;
if (ifr->ifr_addr.sa_family == AF_LINK)
{
struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr;
int a,b,c,d,e,f;
int i;
strcpy(temp, (char *)ether_ntoa(LLADDR(sdl)));
sscanf(temp, “%x:%x:%x:%x:%x:%x”, &a, &b, &c, &d, &e, &f);
sprintf(temp, “%02X:%02X:%02X:%02X:%02X:%02X”,a,b,c,d,e,f);
for (i=0; i<MAXADDRS; ++i)
{
if ((if_names[i] != NULL) && (strcmp(ifr->ifr_name, if_names[i]) == 0))
{
if (hw_addrs[i] == NULL)
{
hw_addrs[i] = (char *)malloc(strlen(temp)+1);
strcpy(hw_addrs[i], temp);
break;
}
}
}
}
cp += sizeof(ifr->ifr_name) + max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len);
}
close(sockfd);
}
– (NSString *)deviceIPAdress {
InitAddresses();
GetIPAddresses();
GetHWAddresses();
return [NSString stringWithFormat:@”%s”, ip_names[1]];
}

ios開発でemojiのサポート判定、有効無効の操作方法

1.絵文字をサポートするかどうかを判断
– (BOOL)supportEmoji
{
BOOL hasEmoji = NO;
#define kPreferencesPlistPath @”/private/var/mobile/Library/Preferences/com.apple.Preferences.plist”
NSDictionary *plistDict = [[NSDictionary alloc] initWithContentsOfFile:kPreferencesPlistPath];
NSNumber *emojiValue = [plistDict objectForKey:@”KeyboardEmojiEverywhere”]; if (emojiValue)
hasEmoji = YES;
else
hasEmoji = NO;
[plistDict release];

return hasEmoji;
}

2.有効または無効
– (void)valueControl:(BOOL)open
{
#define kPreferencesPlistPath @”/private/var/mobile/Library/Preferences/com.apple.Preferences.plist”
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:kPreferencesPlistPath];
[plistDict setValue:[NSNumber numberWithBool:open] forKey:@”KeyboardEmojiEverywhere”];
[plistDict writeToFile:kPreferencesPlistPath atomically:NO];
[plistDict release];
}

ios開発でタッチスクリーン操作の画面で上下または左右にスライドさせるサンプルコード

サンプルコード
infoView=[[UIView alloc] initWithFrame:CGRectMake(25, 110,210, 270)];
infoView.backgroundColor=[UIColor blueColor];
infoView.alpha=0.6;
[self.view addSubview:infoView];
/******************ジェスチャー監視*****************/
UISwipeGestureRecognizer *recognizer;
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[infoView addGestureRecognizer:recognizer];
// recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
// [recognizer setDirection:(UISwipeGestureRecognizerDirectionUp)];
// [self.view addGestureRecognizer:recognizer];
// recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
// [recognizer setDirection:(UISwipeGestureRecognizerDirectionDown)];
// [self.view addGestureRecognizer:recognizer];
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[infoView addGestureRecognizer:recognizer];
//タッチイベント機能の実現
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
if(recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {
NSLog(@”****************左スライド****************”);
}
if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
NSLog(@”****************右スライド****************”);
}
if (recognizer.direction==UISwipeGestureRecognizerDirectionDown){
NSLog(@”****************下スライド****************”);
}
if (recognizer.direction==UISwipeGestureRecognizerDirectionUp){
NSLog(@”****************上スライド****************”);
}
}

iosで2つのファイルは同じかどうか判断方法

サンプルコード
if ([fileManager contentsEqualAtPath:@”FilePath_startnews24aa” andPath:@” FilePath_startnews24bb”]) {
NSLog(@”2つのファイルの差分がございません。”);
}

ios開発にキーボードを好きな色に変更するサンプルコード

サンプルコード:
– (void)textFieldDidBeginEditing:(UITextField *)textField{
NSArray *ws = [[UIApplication sharedApplication] windows];
for(UIView *w in ws){
NSArray *vs = [w subviews];
for(UIView *v in vs){
if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@”UIPeripheralHostView”]){
v.backgroundColor = [UIColor redColor];
}
}
}
}

1 / 41234